如何将AsyncTask添加到没有活动的公共类?

时间:2013-09-13 13:48:38

标签: android android-asynctask

我有一个类,它具有来自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;
}

}

2 个答案:

答案 0 :(得分: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中调用适当的方法。

要将结果返回给活动,请使用界面。请查看以下示例

Can't post response from AsyncTask to MainActivity

答案 1 :(得分:0)

在UI线程中执行网络操作时抛出此操作。这是HoneyComb以来的非法行为。您要做的就是在AsyncTask的doInBackground方法中进行网络操作。

另外请确保您在清单中拥有互联网权限。