简体   繁体   English

由于NetworkonMainThreadException,导致AsyncTask崩溃

[英]AsyncTask crash, due to NetworkonMainThreadException

My application crashes when i tried to go to another page, and this is the error code; 当我尝试转到另一个页面时,我的应用程序崩溃了,这是错误代码;

        01-05 18:49:25.976: E/AndroidRuntime(7596): FATAL EXCEPTION: main
01-05 18:49:25.976: E/AndroidRuntime(7596): android.os.NetworkOnMainThreadException
01-05 18:49:25.976: E/AndroidRuntime(7596):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at com.example.splashscreentwo.JSONParser.makeHttpRequest(JSONParser.java:62)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails$1.run(EmployeePayslip.java:127)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at android.os.Handler.handleCallback(Handler.java:730)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at android.os.Looper.loop(Looper.java:137)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at android.app.ActivityThread.main(ActivityThread.java:5493)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at java.lang.reflect.Method.invoke(Method.java:525)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
01-05 18:49:25.976: E/AndroidRuntime(7596):     at dalvik.system.NativeStart.main(Native Method)

I do not really understand the codes, and unsure what is causing the problem, and following is my java class. 我不太了解代码,不确定导致问题的原因,下面是我的java类。

        package com.example.splashscreentwo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class EmployeePayslip extends Activity {

    private ProgressDialog pDialog;
    String pid;
    TextView employeeName;
    TextView Desc;
    TextView txtCreatedAt;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    JSONArray payslip = null;
    ArrayList<HashMap<String, String>> payslipList;

    // url to get all fulltime employees list
    private static String url_payslip = "http://rollit.sg/FYP/ExportPayslip.php";
    private static final String url_employees_details = "http://rollit.sg/FYP/get_employees_details.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PAYSLIP = "payslip";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PAYSLIPNO = "payslipno";
    private static final String TAG_NETSALARY = "netsalary";
    private static final String TAG_ISSUEDATE = "issuedate";
    private static final String TAG_STARTOFPAYSLIP = "startofpayslip";
    private static final String TAG_ENDOFPAYSLIP = "endofpayslip";
    private static final String TAG_TYPEOFALLOWANCE = "typeofallowance";
    private static final String TAG_ALLOWANCEAMT = "allowanceamt";
    private static final String TAG_ALLOWANCEDATE = "allowancedate";
    private static final String TAG_AVAILABLEALLOWANCE = "availableallowance";
    private static final String TAG_TYPEOFDEDUCTION = "typeofdeduction";
    private static final String TAG_DEDUCTIONAMT = "deductionamt";
    private static final String TAG_DEDUCTIONDATE = "deductiondate";
    private static final String TAG_AGREEDOVERTIMERATE = "agreedovertimerate";
    private static final String TAG_OVERTIMERATE = "overtimerate";
    private static final String TAG_STARTOFOVERTIMEPERIOD = "startofovertimeperiod";
    private static final String TAG_ENDOFOVERTIMEPERIOD = "endofovertimeperiod";
    private static final String TAG_BASICSALARY = "basicsalary";
    private static final String TAG_EXTRAPAYMENT = "extrapayment";

    private static final String TAG_EMPLOYEE = "employ";
    private static final String TAG_SALARY = "pay";
    private static final String TAG_DESCRIPTION = "description";




    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employeepayslip);




     payslipList = new ArrayList<HashMap<String, String>>();

     // Loading all fulltime employees in Background Thread
     // getting employee details from intent
     Intent i = getIntent();

     // getting employee id (pid) from intent
     pid = i.getStringExtra(TAG_PID);


     new GetEmployeeDetails().execute();

    }
    class GetEmployeeDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EmployeePayslip.this);
            pDialog.setMessage("Loading employees details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting employee details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
             runOnUiThread(new Runnable() {
                 public void run() {
                     // Check for success tag
                     int success;
                     try {
                         // Building Parameters
                         List<NameValuePair> params = new ArrayList<NameValuePair>();
                         params.add(new BasicNameValuePair("pid", pid));

                         // getting employee details by making HTTP request
                         // Note that employee details url will use GET request
                         JSONObject json = jParser.makeHttpRequest(
                                 url_employees_details, "GET", params);

                         // check your log for json response
                         Log.d("Employee Details", json.toString());

                         // json success tag
                         success = json.getInt(TAG_SUCCESS);
                         if (success == 1) {
                             // successfully received employee details
                             JSONArray employeeObj = json
                                     .getJSONArray(TAG_EMPLOYEE); // JSON Array

                             // get first employee object from JSON Array
                             JSONObject employee = employeeObj.getJSONObject(0);

                             // employee with this pid found
                             // Edit Text
                             employeeName = (TextView) findViewById(R.id.employeeName);

                             Desc = (TextView) findViewById(R.id.department);

                             // display employee data in EditText
                             employeeName.setText(employee.getString(TAG_NAME));

                             Desc.setText(employee.getString(TAG_DESCRIPTION));

                         }else{
                             // employee with pid not found
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                 }
             });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
}

So, what is causing the problem? 那么,是什么引起了问题呢? Any help is greatly appreciated, thanks! 非常感谢任何帮助,谢谢!

Remove 去掉

 runOnUiThread(new Runnable() {
             public void run() {

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

You don't need this coz doInbackground is invoked on the background thread. 您不需要在后台线程上调用此coz doInbackground If you need to update ui you can do in onPostExecute which is invoked on the ui thread. 如果需要更新ui,可以在ui线程上调用的onPostExecute中执行。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Initialize in onCreate onCreate初始化

employeeName = (TextView) findViewById(R.id.employeeName);
Desc = (TextView) findViewById(R.id.department);

You should also move employeeName.setText(employee.getString(TAG_NAME)) and Desc.setText(employee.getString(TAG_DESCRIPTION)) to onPostExecute . 您还应该将employeeName.setText(employee.getString(TAG_NAME))Desc.setText(employee.getString(TAG_DESCRIPTION))移到onPostExecute

The result of the background computation is returned in doInbackground and is param to onPostExecute . 后台计算的结果在doInbackground返回,并且是onPostExecute参数。 So based on the result returned update ui in onPostExecute accordingly 因此,根据返回的结果,在onPostExecute相应地更新ui

Read the 4 Steps @ 阅读4个步骤@

http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/os/AsyncTask.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM