2017-01-05 4 views
1

Я пытаюсь обновить textview на основе возвращаемого значения из URL. Первый URL-адрес, возвращаемое значение обновляет текстовое представление. но второй url, textview не обновляется с данными, он только пустой.Android - извлекает данные из разных php/url и обновляет текстовое представление на основе возвращаемого значения url

общественного класса MainActivity расширяет AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds 
public static final int CONNECTION_TIMEOUT = 10000; 
public static final int READ_TIMEOUT = 15000; 
TextView textHost, textOS; 

StringBuilder result, resultOS; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    textHost = (TextView) findViewById(R.id.textHost); 
    textOS = (TextView) findViewById(R.id.textOS); 

    //Make call to AsyncRetrieve 
    new AsyncRetrieve().execute(); 
} 

private class AsyncRetrieve extends AsyncTask<String, String, String> 
{ 
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this); 
    HttpURLConnection conn, connOS; 
    URL url, urlOS = null; 

    //this method will interact with UI, here display loading message 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     pdLoading.setMessage("\tLoading..."); 
     pdLoading.setCancelable(false); 
     pdLoading.show(); 

    } 

    // This method does not interact with UI, You need to pass result to onPostExecute to display 
    @Override 
    protected String doInBackground(String... params) 
    { 
     try 
     { 
      // Enter URL address where your php file resides 
      url = new URL("http://192.168.1.13/fyp/Cpu.php"); 
      urlOS = new URL ("http://192.168.1.13/fyp/Name.php"); 

     } catch (MalformedURLException e) 
      { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return e.toString(); 
      } 

     try 
     { 
      // Setup HttpURLConnection class to send and receive data from php 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(READ_TIMEOUT); 
      conn.setConnectTimeout(CONNECTION_TIMEOUT); 
      conn.setRequestMethod("GET"); 

      conn.setDoOutput(true); 

      connOS = (HttpURLConnection) urlOS.openConnection(); 
      connOS.setReadTimeout(READ_TIMEOUT); 
      connOS.setConnectTimeout(CONNECTION_TIMEOUT); 
      connOS.setRequestMethod("GET"); 

      // setDoOutput to true as we recieve data from json file 
      connOS.setDoOutput(true); 

     } catch (IOException e1) 
      { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      return e1.toString(); 
      } 

     try 
     { 
      int response_code = conn.getResponseCode(); 
      int responseOS = connOS.getResponseCode(); 

      // Check if successful connection made 
      if (response_code == HttpURLConnection.HTTP_OK) 
      { 
       // Read data sent from server 
       InputStream input = conn.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       result = new StringBuilder(); 
       String line; 

       while ((line = reader.readLine()) != null) 
       { 
        result.append(line); 
       } 

       // Pass data to onPostExecute method 
       return (result.toString()); 

      } 

      if (responseOS == HttpURLConnection.HTTP_OK) 
      { 
       // Read data sent from server 
       InputStream input = connOS.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       resultOS = new StringBuilder(); 
       String line; 

       while ((line = reader.readLine()) != null) 
       { 
        resultOS.append(line); 
       } 

       // Pass data to onPostExecute method 
       return (resultOS.toString()); 
      } 

      else 
      { 
       return ("unsuccessful"); 
      } 

     } catch (IOException e) 
      { 
      e.printStackTrace(); 
      return e.toString(); 
      } finally 
      { 
       conn.disconnect(); 
       connOS.disconnect(); 
      } 


    } 

    public void output() 
    { 

      textHost.setText(result); //the textview is updated based on data fetch on url 
      textOS.setText(resultOS); //the data does not show 

    } 

     // this method will interact with UI, display result sent from doInBackground method 
    @Override 
    protected void onPostExecute(String result) 
    { 
     super.onPostExecute(result); 

     pdLoading.dismiss(); 

      output(); 
      //textHost.setText(result.toString()); 
      //textOS.setText(resultOS.toString()); 


    } 

} 

}

+0

Добро пожаловать в StackOverflow. Вам нужно будет отладить эту программу и предоставить больше информации, так как может быть много причин, почему этого не происходит (сервер вниз, не подключен к интернету и т. Д.). См. Это руководство для отладки небольших программ: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

ответ

0

// этот метод будет взаимодействовать с UI, результат отображения отправленного от метода doInBackground

@Override 
protected void onPostExecute(String result) 
{ 
    super.onPostExecute(result); 

    pdLoading.dismiss(); 

     output(); 
      //Uncomment the below line 
     textHost.setText(result.toString()); 
     textOS.setText(resultOS.toString()); 


} 
+0

спасибо. я уже раскомментировал код, но все же результат не появился в textOS. это просто пусто. Я думаю, что он не выполняет код в doInBackground. –

 Смежные вопросы

  • Нет связанных вопросов^_^