2013-01-16 165 views
0

我是新來的android,我希望有人能幫助我。我有一個活動學院和一個按鈕。按鈕時顯示ListView點擊

這是我的XML佈局browse_faculty:

<Button 
    android:onClick="searchFSTEHandler" 
    android:id="@+id/bFSTE" 
    android:layout_width="220dp" 
    android:layout_height="80dp" 
    android:layout_alignLeft="@+id/bFBE" 
    android:layout_below="@+id/bFBE" 
    android:layout_marginTop="20dp" 
    android:text="@string/fste" /> 

,這是我的系活性,其顯示的按鈕: 我使用意圖來查看的ListView

public class Faculty extends Activity{ 

    @Override 
    protected void onCreate(Bundle BrowseFaculty) { 
     // TODO Auto-generated method stub 
     super.onCreate(BrowseFaculty); 
     setContentView(R.layout.browse_faculty); 
    } 

    //on the XML,this is the "searchFSTEHandler" i want to use to show ListView 
    public void searchFSTEHandler(View target){ 
     Intent courseList = new Intent(this, HttpActivity.class); 
     startActivity(courseList); 
    } 
} 

和下面是 「HttpActivity」類是顯示我的ListView的類。這個類讀取一個php文件,該文件從MySQL服務器獲取數據並轉換爲JSON數據,然後將其解析爲數組列表。

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.ArrayList; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 



import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.ListActivity; 
import android.widget.ArrayAdapter; 

public class HttpActivity extends ListActivity { 

public String f1 = "FSTE"; 




@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.faculty_course); 


    new getHttp().execute(); 

    getHttp test =new getHttp(); 


    String strJsonData = test.doInBackground(f1); 

    // Convert String JSON data to Java class 
    ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData); 

    //Create an ArrayAdapter which shows the ArrayList data 
    this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse)); 



} 




private class getHttp extends AsyncTask<String, Void, String> { 

    public getHttp() { 











    } 

    @Override 
    protected String doInBackground(String... faculty) { 



    InputStream is = null; 
    try { 
     URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE"); 
     URLConnection con = url.openConnection(); 
     con.setConnectTimeout(10000); 
     con.setReadTimeout(10000); 
     is = con.getInputStream(); 

     BufferedReader br = new BufferedReader(
       new InputStreamReader(is)); 
     StringBuffer sb = new StringBuffer(); 
     String str; 
     while ((str = br.readLine()) != null) { 
      sb.append(str); 
     } 
     return sb.toString(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
     return ""; 

    } finally { 
     try { 
      if (is != null) 
       is.close(); 
     } catch (IOException e2) { 
      e2.printStackTrace(); 
     } 
    } 


} 

//------------------------------------------------------ 
    private ArrayList<Courses> parseJsonData(String strJson) { 
     ArrayList<Courses> Course = new ArrayList<Courses>(); 

     try { 
      // Generate JSONArray object by JSON String data 
      JSONArray arr = new JSONArray(strJson); 

      //from the JSONArray, get one element (row) of JSONData 
      for (int i = 0; i < arr.length(); i++) { 

       //Get JSON Object which is one element of the array 
       JSONObject ob = arr.getJSONObject(i); 

       Courses exam = new Courses(); 
       //get the value by key, and set to exam class 
       exam.setCode(ob.optString("code")); 

       //save exam class to exam array list 
       Course.add(exam); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return Course; 
    } 





} 









} 

的應用程序崩潰,只要我按一下按鈕,並給出了一個錯誤: 「android.os.NetworkOnMainThreadException」

幫助請!

回答

0

您不能在主線程中進行HTTP調用,它們需要很長時間並且會導致UI無響應。你需要在AsyncTask中完成。

+0

請詳細說明更多或其他aproches我可以請...林洙新本:/ –

+0

AsyncTask是一個你可以繼承的類,它可以在另一個線程上運行一個函數,而不需要有一個永久線程。 Http調用不能在主線程中發生,所以它們通常是在AsyncTask中完成的。例如:http://pcfandroid.wordpress.com/2011/07/14/http-post-with-asynctask-android-tutorial/ –

1

您遇到的問題是您正在嘗試執行的網絡操作不能也不應該在主UI線程上執行。這樣做會導致ANR(Android Not Responding),這正是您剛剛獲得的錯誤。你想要做的是將你的代碼移動到一個單獨的線程或一個AsyncTask,它將在不同的線程使用方法在後臺執行此操作,該方法無法訪問主UI線程上的視圖。例如,

private class ExampleOperation extends AsyncTask<String, Void, String> { 

    public ExampleOperation() { //ctor } 

    @Override 
    protected void onPreExecute() { 
     //things that you want to initialize and maybe show dialog to user. 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     //this is where you perform that network related operation. 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     //this is where get the results from the network related task. 
    } 

    @Override 
    protected void onProgressUpdate(Void... values) { 
     //you can update your progressbar if any; otherwise omit method. 
    } 

} 

然後,所有你需要做的就是調用任何你想使用它的AsyncTask:new ExampleOperation().execute();

+0

謝謝,另一件事情...... ExampleOperation的構造函數是什麼? –

+0

它和其他類構造函數幾乎相同;它會是:'public ExampleOperation(){}' –

+0

請記住接受幫助您完成任務的最佳答案;這是給作者和社區的功勞。 –