0

我有一个类,它具有来自 url 的 getJSON 功能。我认为代码没有问题。但它给了我android.os.NetworkOnMainThreadException。我应该使用 AsyncTask 但我自己不能这样做。我们可以将 AsyncTask 添加到任何类,比如我的 JsonCreator 类吗?我的班级定义是;

public class JsonCreator{
private String Url = Constants.url;
JSONObject result = null;
JSONArray json = null;
Connect connect = new Connect();

public JSONArray getJson(String command, String[] parameter, int connectionMode){
    String urlParameter = null;

    //Creating parameter which will be added to the end of the URL
    for(int i=0 ; i<parameter.length-1 ; i=i+2){
        if(i == 0)
            urlParameter = "?" + parameter[i] + "=" + parameter[i+1];
        else
            urlParameter = urlParameter + "&" + parameter[i] + "=" + parameter[i+1];
    }

    //First Scenario
    if(connectionMode == 1){

        //Control host availability and take Json Array
        try {
            result = connect.connect(Url+command+urlParameter);
            Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
            json = result.getJSONArray("d");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Save JsonArray to SharedPrefs
        Constants.saveJSONArray(Constants.context, "Json", command, json);
    }

    //Second Scenario
    else if(connectionMode == 2){

        //Control host availability and take Json Array
        try {
            result = connect.connect(Url+command+urlParameter);
            Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
            json = result.getJSONArray("d");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //If json can not be taken from URL, Search for data from SharedPrefs
        if(json == null || !Constants.hostReachability){
            try {
                json = Constants.loadJSONArray(Constants.context, "Json", command);
            } catch (JSONException e) {
                Constants.connectionProblem = "No Data";
                e.printStackTrace();
            }
        }
    }
    //Third Scenario
    else if(connectionMode == 3){

        //Take data from SharedPrefs
        try {
            json = Constants.loadJSONArray(Constants.context, "Json", command);
        } catch (JSONException e) {
            Constants.connectionProblem = "No Data";
            e.printStackTrace();
        }

        //If the data from SharedPref can not be found, Take json from URL
        if(json == null){
            //Control host availability and take Json Array
            try {
                result = connect.connect(Url+command+urlParameter);
                Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
                json = result.getJSONArray("d");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return json;
}

public JSONArray getJson(String command, String[] parameter){
    String urlParameter = null;
    //Creating parameter which will be added to the end of the URL
    for(int i=0 ; i<parameter.length ; i=i+2){
        if(i == 0)
            urlParameter = "?" + parameter[i] + "=" + parameter[i+1];
        else
            urlParameter = urlParameter + "&" + parameter[i] + "=" + parameter[i+1]; 
    }
    //Take json from server
    try {
        result = connect.connect(Url+command+urlParameter);
        Constants.hostReachability = Constants.isHostRechable(Url+command+urlParameter);
        json = result.getJSONArray("d");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

}
4

2 回答 2

2

你得到android.os.NetworkOnMainThreadException是因为你在 ui 线程上运行网络相关的操作。使用AsyncTaskThread

http://developer.android.com/reference/android/os/AsyncTask.html

检查上面链接中线程规则下的主题

像这样调用 asynctask

  new TheTask().execute(); // you can pass values to asynctask doinbackground

然后

public class TheTask extends AsyncTask <Void,Void,Void>
{

@Override
protected void onPreExecute() {
    super.onPreExecute();
            // display progress dialog

}
@Override
protected Void doInBackground(Void... params) {
        // your background computation. do not update ui here
        // your getjson method code here
    return null; //return result of doinbackground computation 
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
         //dismiss progress dialog
         // recieve result and update ui
    }
}

正如 codemagic 建议的那样,您的类可以扩展 asynctask 并在 doInbackground 中调用适当的方法。

要将结果返回给活动,请使用接口。检查下面的示例

无法将 AsyncTask 的响应发布到 MainActivity

于 2013-09-13T13:54:27.580 回答
0

当您在 UI 线程中执行网络操作时会引发此问题。这是非法的,因为 HoneyComb。您所要做的就是在 AsyncTask 的 doInBackground 方法中进行网络操作。

还要确保您在清单中拥有互联网权限。

于 2013-09-13T13:52:29.463 回答