在下面的代码中,我在运行Android项目时遇到错误
代码:
try {
Gson gson = new Gson();
String json = gson.toJson(stockDetailData);
String json1 = gson.toJson(stockMainData);
String json2 = gson.toJson(pledgerData);
JSONObject jo = new JSONObject();
jo.put("stockDetailData", json.toString());
jo.put("stockMainData", json1.toString());
jo.put("pledgerData", json2.toString());
jo.put("company_id", "4");
URL url = new URL("http://127.0.0.1:180/AfaqTraders/index.php/sale/saveVoucher");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
} catch(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
错误: android.os.NetworkOnMainThreadException
我一直在寻找错误,但我无法找到它。谁能告诉我这里我做错了什么?
答案 0 :(得分:4)
因为您正在进行网络操作 Main UI thread
如果您使用线程进行网络操作 然后你可以使用这段代码
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
在OnCreate()
但是使用上述操作的错误做法,应该使用android提供的AsyncTask
类来正确处理网络操作without blocking UI thread
。
您可以访问此LINK
了解详情或者可以使用以下代码
private class UploadFiles extends AsyncTask<String, Void, Void> {
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}
protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}
protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}
您可以通过编写
来简单地调用此类 new UploadFiles ().execute(new String[]{//YOUR LINK});
答案 1 :(得分:1)
您应该使用Asynctask,线程,处理程序而不是主线程连接到网络。如果您尝试使用主UIThread连接(执行长时间操作),您将看到此错误。
答案 2 :(得分:0)
当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask或IntentService w
中运行您的代码请参阅this示例,了解如何在asyncTask中处理网络操作
答案 3 :(得分:0)
you should use asynctask [asynctask][1]
[1]: http://developer.android.com/reference/android/os/AsyncTask.html
> class async extends AsyncTask<Params, Progress, Result>
//Params used in the asynctask
//Progress for progress bar
//Result here the result of parsing
{@Override
protected void onPreExecute() {
//before parsing you can launch a progress bar
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
//processing after parsing
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... params) {
// parsing here
return null;
}}