我正在開發一個使用MySQL數據庫的登錄應用程序。我正在使用數據庫包中的JSONParser連接到本地mysql數據庫我收到以下錯誤,請有人幫助我。我搜索了這個錯誤,但我得到的是使用AsyncTask,但我不知道在哪裏使用,如何使用以及Mainthread是什麼。 請有人編輯我的代碼,並解釋或交相關代碼... 「android.os.NetworkonMainThreadException」當我從運行4.2 genymotion模擬器應用程序的錯誤...如何在JSON解析器中爲我的代碼編寫AsyncTask?
package com.android.database;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}``
您嘗試調用UI線程網絡請求你應該這樣做在新的線程或的AsyncTask的[android.os.NetworkOnMainThreadException] – 2015-03-02 12:24:26
可能重複(http://stackoverflow.com/questions/6343166 /機器人-OS-networkonmainthreadexception) – 2015-03-02 12:29:58