2016-03-12 68 views
0

我使用json從php文件加載信息。然後,我試圖在頁面加載後立即在列表視圖中顯示它。不過,我在我的onCreate()方法中,它不會讓我在UI線程上執行網絡操作。我在哪裏可以把下面的代碼來代替:從在線數據庫加載信息以顯示在活動

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_chores); 

    bChore = (Button) findViewById(R.id.addChore); 

    bChore.setOnClickListener(this); 

    Bundle extras = getIntent().getExtras(); 
    final String user = extras.getString("username"); 


    //The URL is the location of the PHP file to validate a user 
    String requestURL = SERVER_ADDRESS+"FetchChoreData.php"; 

    URL url; 
    Chore returnedChore = null; 
    try { 
     //Opens the connection to the PHP files 
     //Sets the conditions of the connection 
     url = new URL(requestURL); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(CONNECTION_TIMEOUT); 
     conn.setConnectTimeout(CONNECTION_TIMEOUT); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     //Opens an output stream to send the data to be verified 
     // and then closes the all output streams and flushes the output writer 
     OutputStream os = conn.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 

     Uri.Builder builder = new Uri.Builder() 
       .appendQueryParameter("username",user); 

     String query = builder.build().getEncodedQuery(); 

     writer.write(query); 
     writer.flush(); 
     writer.close(); 
     os.close(); 
     //saves the response code to ensure connection was succesful 
     int code = conn.getResponseCode(); 
     Log.d("code", Integer.toString(code)); 

     //Opens an input stream to retrieve verified data back from the server 
     //Starts a String Builder to read the data off the input 
     //Closes the BufferedReader once it has finished building the string 
     InputStream responseStream = new BufferedInputStream(conn.getInputStream()); 
     BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); 
     String line; 
     StringBuilder stringBuilder = new StringBuilder(); 
     while ((line = responseStreamReader.readLine()) != null) 
      stringBuilder.append(line + "/n"); 
      responseStreamReader.close(); 


      String response = stringBuilder.toString(); 
      Log.d("response",response); 

      JSONObject jsonResponse = new JSONObject(response); 

      //Creates a JSON object from the string 
      ArrayList<String> chores = new ArrayList<String>(); 
      JSONArray choresArray = jsonResponse.getJSONArray("chore"); 
      for(int i=0; i < choresArray.length() ; i++) { 
       JSONObject chore = choresArray.getJSONObject(i); 
       String current_chore = chore.optString("chore_name"); 
       String name = chore.optString("child_username"); 
       String points = chore.optString("point_value"); 

       String currentChore = ""; 
       if(name==null) 
        currentChore = current_chore + "\t" + "Not Claimed" + "\t" + points; 
       else 
        currentChore = current_chore + "\t" + name + "\t" + points; 
       chores.add(currentChore); 
       Log.d("Output", currentChore); 

      } 


      ArrayAdapter<String> choreAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, chores); 

      ListView listView = (ListView) findViewById(R.id.choreList); 
      listView.setAdapter(choreAdapter); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

查看如何使用AsyncTask或使用像Volley這樣的庫 –

回答

0

你,或許,應該把這個代碼AsyncTask並填充AsyncTask'sonPostExecute你的UI。只要確保不要在AsyncTask的doInBackground中更新UI,就在那裏進行數據提取。

實際上,您最好使用帶有setRetainInstance(true)的非UI片段與AsyncTask一起使用,但您可以使用Google的。

相關問題