0

我是android新手,希望有人可以在这里帮助我。我有一个活动学院和一个按钮。

这是我的 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" />

这是我的显示按钮的教师活动:我使用 Intent 来查看 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”

请帮忙 !

4

2 回答 2

1

您遇到的问题是您尝试执行的网络操作不能也不应该在主 UI 线程上执行。这样做会导致ANR (Android Not Responding),这正是您刚刚遇到的错误。您想要做的是将您的代码移动到一个单独的线程,或者移动到一个AsyncTask将在不同线程的后台执行此操作的doInBackground()方法,该方法无法访问您在主 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();

于 2013-01-16T00:23:53.857 回答
0

您不能在主线程中进行 HTTP 调用,它们花费的时间太长并且会使 UI 无响应。您需要在 AsyncTask 中执行此操作。

于 2013-01-16T00:09:04.240 回答