0
这是我的代码。我正在尝试扩展AsyncTask
,但它不起作用。这是我的代码。 运行我的应用程序时显示NetworkOnMainThread
异常。我是android新手,我需要开发一个登录系统。如何在此代码中实现AsyncTask。
public class JSONParser extends AsyncTask<String,Void,JSONObject>{
static InputStream mInputStream=null;
static JSONObject mJsonObject=null;
static String json="";
String url="";
List<NameValuePair> params=null;
public JSONParser() {
}
public JSONObject getJsonFromURL(String url,List<NameValuePair> params){
url=this.url;
params=this.params;
return doInBackground();
}
protected JSONObject doInBackground(String... params) {
try{
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
mInputStream=httpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(mInputStream,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line= null;
while((line=bufferedReader.readLine())!=null){
sb.append(line).append("\n");
}
bufferedReader.close();
json=sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mJsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return mJsonObject;
}
}
我不知道是不是正确的方法。 请帮帮我。 httpPost.setEntity(new UrlEncodedFormEntity(params)); 这条线显示我的错误,不知道如何删除它。广东话申请的String []
你究竟在哪里扩展AsyncTask? –
在我看来,你需要在AsyncTask中包装你的getJsonFromURL函数来获得结果。网络活动无法在主线程上执行,这就是为什么使用Async任务。它在另一个线程中运行该活动。 –
看到我的答案一些如何可以帮助你 – Developer