如何从AsyncTask的数据返回到主线程

如何从AsyncTask的数据返回到主线程

本文介绍了如何从AsyncTask的数据返回到主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要到的JSONObject返回主线程。但是当我试图c将其返回以下错误运行$ C $。

  6月2日至6日:14:36.490:E / AndroidRuntime(769):致命异常:主要
6月2日至6日:14:36.490:E / AndroidRuntime(769):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.dataread / com.example.dataread.MainActivity}:显示java.lang.NullPointerException
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.os.Handler.dispatchMessage(Handler.java:99)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.os.Looper.loop(Looper.java:137)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread.main(ActivityThread.java:5039)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在java.lang.reflect.Method.invokeNative(本机方法)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在java.lang.reflect.Method.invoke(Method.java:511)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在dalvik.system.NativeStart.main(本机方法)
6月2日至6日:14:36.490:E / AndroidRuntime(769):致:显示java.lang.NullPointerException
6月2日至6日:14:36.490:E / AndroidRuntime(769):在com.example.dataread.MainActivity.onCreate(MainActivity.java:37)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.Activity.performCreate(Activity.java:5104)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
6月2日至6日:14:36.490:E / AndroidRuntime(769):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
6月2日至6日:14:36.490:E / AndroidRuntime(769):11 ...更多

这是我的code:

 公共接口Asynchtask
{
无效processFinish(JSONObject的结果);}
公共类MainActivity扩展ListActivity实现Asynchtask
{    JSONfunctions JS =新JSONfunctions();
    的JSONObject retunfromAsyncTask;
    //公共静态的JSONObject dataFromAsyncTask;
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        js.delegate =这一点;
        新JSONfunctions()执行(http://192.168.6.43/employees.php);        的setContentView(R.layout.listplaceholder);
          ArrayList的<&HashMap的LT;字符串,字符串>> MYLIST =新的ArrayList<&HashMap的LT;字符串,字符串>>();        尝试{                JSONArray员工= retunfromAsyncTask.getJSONArray(员工);                的for(int i = 0; I< employees.length();我++){                    JSONArray E = employees.getJSONArray(I)
                    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                    map.put(姓名,EMP名:+ e.getString(0)++ e.getString(1)++ e.getString(2));
                    map.put(电子邮件ID,电子邮件ID:+ e.getString(3));
                    map.put(电话没有,电话号码:+ e.getString(4));                    mylist.add(地图);
                }
            }赶上(JSONException E){
                 Log.e(log_tag,错误分析数据+ e.toString());
            }            ListAdapter适配器=新SimpleAdapter(这一点,MYLIST,R.layout.activity_main,
                            新的String [] {姓名,电子邮件ID,手机无},
                            新的INT [] {R.id.item_title,R.id.item_emailid,R.id.item_phoneno});
           setListAdapter(适配器);            最终的ListView LV = getListView();
            lv.setTextFilterEnabled(真);
                }
    @覆盖
    公共无效processFinish(JSONObject的结果){
        // TODO自动生成方法存根
        retunfromAsyncTask =结果;    }}
公共类JSONfunctions扩展的AsyncTask<弦乐,无效的JSONObject> {    公共Asynchtask委托= NULL;     InputStream为;
     字符串结果;
     的JSONObject jArray;
    @覆盖
    受保护的JSONObject doInBackground(字符串... PARAMS){
        // TODO自动生成方法存根
        // HTTP POST
        尝试{
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httppost =新HttpPost(PARAMS [0]);
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();        }赶上(例外五){
                Log.e(log_tag,在HTTP连接错误+ e.toString());
        }
        尝试{
             读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
             StringBuilder的SB =新的StringBuilder();
             串线= NULL;
             而((行= reader.readLine())!= NULL){
                     sb.append(行+\\ n);
             }
             is.close();
             结果= sb.toString();     }赶上(例外五){
             Log.e(log_tag,错误转换结果+ e.toString());
     }     尝试{         jArray =新的JSONObject(结果);       // MainActivity.dataFromAsyncTask = jArray;
     }赶上(JSONException E){
             Log.e(log_tag,错误分析数据+ e.toString());
     }     返回jArray;
      //响应转换为字符串    }
    @覆盖
    保护无效onPostExecute(JSONObject的结果)
    {
          delegate.processFinish(结果);    }
}

Manifestfile

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.example.dataread
    安卓版code =1
    机器人:=的versionName1.0>    <用途-SDK
        安卓的minSdkVersion =4
        机器人:targetSdkVersion =17/>
    <使用许可权的android:NAME =android.permission.INTERNET对/>    <应用
        机器人:allowBackup =真
        机器人:图标=@绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名字=com.example.dataread.MainActivity
            机器人:标签=@字符串/ APP_NAME>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>                <类机器人:名字=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
    < /用途>< /清单>


解决方案

得到结果返回的主线程,你需要使用AsyncTask.get()方法,使UI线程等到 doInBackground 未执行完毕,但得到()方法调用冻结的主UI线程,直到 doInBackground 计算是不完整的。启动的AsyncTask 使用get()方法为:

 字符串str_result =新
             。JSONfunctions()执行(http://192.168.6.43/employees.php)获得();

移动此行一个线程内以避免UI线程冻结



利用使用的AsyncTask 的移动要与 doInBackground 里面onPostExecute计算为:

 公共类JSONfunctions扩展
                  AsyncTask的<弦乐,无效的JSONObject> {    公共Asynchtask委托= NULL;     InputStream为;
     字符串结果;
     的JSONObject jArray;
    @覆盖
    受保护的JSONObject doInBackground(字符串... PARAMS){
      //你的code这里....
     返回jArray;
      //响应转换为字符串    }
    @覆盖
    保护无效onPostExecute(JSONObject的结果)
    {
          JSONArray员工=
                result.getJSONArray(员工);
           //你的code这里...
      ListAdapter适配器=新SimpleAdapter(MainActivity.this,MYLIST,
                                             R.layout.activity_main,
                            新的String [] {姓名,电子邮件ID,手机无},
                            新的INT [] {R.id.item_title,R.id.item_emailid
                                      ,R.id.item_phoneno});
           MainActivity.this.setListAdapter(适配器);            最终的ListView LV = MainActivity.this.getListView();
             // ....
    }
}

I want to return the Jsonobject to main thread. But when i tried to run the code it returns the following error.

02-06 06:14:36.490: E/AndroidRuntime(769): FATAL EXCEPTION: main
02-06 06:14:36.490: E/AndroidRuntime(769): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dataread/com.example.dataread.MainActivity}: java.lang.NullPointerException
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.os.Looper.loop(Looper.java:137)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread.main(ActivityThread.java:5039)
02-06 06:14:36.490: E/AndroidRuntime(769):  at java.lang.reflect.Method.invokeNative(Native Method)
02-06 06:14:36.490: E/AndroidRuntime(769):  at java.lang.reflect.Method.invoke(Method.java:511)
02-06 06:14:36.490: E/AndroidRuntime(769):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-06 06:14:36.490: E/AndroidRuntime(769):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-06 06:14:36.490: E/AndroidRuntime(769):  at dalvik.system.NativeStart.main(Native Method)
02-06 06:14:36.490: E/AndroidRuntime(769): Caused by: java.lang.NullPointerException
02-06 06:14:36.490: E/AndroidRuntime(769):  at com.example.dataread.MainActivity.onCreate(MainActivity.java:37)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.Activity.performCreate(Activity.java:5104)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-06 06:14:36.490: E/AndroidRuntime(769):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-06 06:14:36.490: E/AndroidRuntime(769):  ... 11 more

This is my code:

public interface Asynchtask
{
void processFinish(JSONObject result);

}


public class MainActivity extends ListActivity implements Asynchtask
{

    JSONfunctions js= new JSONfunctions();
    JSONObject retunfromAsyncTask;
    //public static JSONObject dataFromAsyncTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        js.delegate = this;
        new JSONfunctions().execute("http://192.168.6.43/employees.php");

        setContentView(R.layout.listplaceholder);
          ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();



        try {

                JSONArray  employees = retunfromAsyncTask.getJSONArray("Employees");

                for(int i=0;i<employees.length();i++){

                    JSONArray e = employees.getJSONArray(i);
                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put("name", "emp name:" + e.getString(0)+" "+e.getString(1)+" "+e.getString(2));
                    map.put("email id", "email id: " +  e.getString(3));
                    map.put("phone no", "phone no: " +  e.getString(4));

                    mylist.add(map);
                }
            }catch(JSONException e)        {
                 Log.e("log_tag", "Error parsing data "+e.toString());
            }

            ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_main,
                            new String[] { "name", "email id","phone no" },
                            new int[] { R.id.item_title, R.id.item_emailid ,R.id.item_phoneno});
           setListAdapter(adapter);

            final ListView lv = getListView();
            lv.setTextFilterEnabled(true);
                }




    @Override
    public void processFinish(JSONObject result) {
        // TODO Auto-generated method stub
        retunfromAsyncTask=result;

    }

}


public class JSONfunctions extends AsyncTask<String, Void, JSONObject> {

    public Asynchtask delegate=null;

     InputStream is;
     String result ;
     JSONObject jArray;


    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub


        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(params[0]);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
        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();
             result=sb.toString();

     }catch(Exception e){
             Log.e("log_tag", "Error converting result "+e.toString());
     }

     try{

         jArray = new JSONObject(result);

       //  MainActivity.dataFromAsyncTask=jArray;
     }catch(JSONException e){
             Log.e("log_tag", "Error parsing data "+e.toString());
     }

     return jArray;
      //convert response to string

    }
    @Override
    protected void onPostExecute(JSONObject result)
    {
          delegate.processFinish(result);

    }
}

Manifestfile

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dataread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.dataread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
解决方案

to get result back in Main Thread you will need to use AsyncTask.get() method which make UI thread wait until execution of doInBackground is not completed but get() method call freeze the Main UI thread until doInBackground computation is not complete . start your AsyncTask using get() method as :

String str_result=new
             JSONfunctions().execute("http://192.168.6.43/employees.php").get();

move this line inside a Thread to avoid freezing of UI thread


Second and right way to utilize the use of AsyncTask move your code which you want to update with the result of doInBackground computation inside onPostExecute as :

public class JSONfunctions extends
                  AsyncTask<String, Void, JSONObject> {

    public Asynchtask delegate=null;

     InputStream is;
     String result ;
     JSONObject jArray;


    @Override
    protected JSONObject doInBackground(String... params) {
      // your code here....
     return jArray;
      //convert response to string

    }
    @Override
    protected void onPostExecute(JSONObject result)
    {
          JSONArray  employees =
                result.getJSONArray("Employees");
           // your code here...
      ListAdapter adapter = new SimpleAdapter(MainActivity.this, mylist ,
                                             R.layout.activity_main,
                            new String[] { "name", "email id","phone no" },
                            new int[] { R.id.item_title, R.id.item_emailid
                                      ,R.id.item_phoneno});
           MainActivity.this.setListAdapter(adapter);

            final ListView lv = MainActivity.this.getListView();
             //....
    }
}

这篇关于如何从AsyncTask的数据返回到主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:14