由于NetworkonMainThreadException,AsyncTask崩溃

时间:2014-01-05 10:57:59

标签: java android networking android-asynctask

当我尝试转到另一个页面时,我的应用程序崩溃了,这是错误代码;

        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)

我不太了解代码,也不确定导致问题的原因,以下是我的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();
        }
    }
}

那么,是什么导致了这个问题呢?非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:3)

删除

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

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

您不需要在后台线程上调用此coz doInbackground。如果你需要更新ui,你可以在ui线程上调用的onPostExecute中进行更新。

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

onCreate

中初始化
employeeName = (TextView) findViewById(R.id.employeeName);
Desc = (TextView) findViewById(R.id.department);

您还应将employeeName.setText(employee.getString(TAG_NAME))Desc.setText(employee.getString(TAG_DESCRIPTION))移至onPostExecute

后台计算的结果在doInbackground中返回,并且是onPostExecute的参数。所以基于结果返回更新ui onPostExecute相应地

阅读4个步骤@

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