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