在执行doInBackground异步任务时出错() [英] Async Task An error occured while executing doInBackground()

查看:99
本文介绍了在执行doInBackground异步任务时出错()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 previous问题

我得到NullPointor例外。所以,我做我的code一些变化,现在进度条显示出来,但得到下面的错误。

  11-17 23:39:51.373:ERROR / AndroidRuntime(495):未捕获的处理程序:螺纹AsyncTask的#1,由于未捕获的异常退出
11-17 23:39:51.373:ERROR / AndroidRuntime(495):java.lang.RuntimeException的:一个错误而执行doInBackground发生()
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在android.os.AsyncTask $ 3.done(AsyncTask.java:200)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.FutureTask中$ Sync.innerSetException(FutureTask.java:273)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:307)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:561)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):在java.lang.Thread.run(Thread.java:1096)
11-17 23:39:51.373:ERROR / AndroidRuntime(495):java.lang.RuntimeException的:所致。内螺纹已经不叫尺蠖prepare无法创建处理器()
 

code是...

 公共类JsonExampleActivity扩展ListActivity {
/ **第一次创建活动时调用。 * /
ProgressDialog mDialog;

最终的字符串变量=a.c.b;
JSONFunction JSONfunction;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);

    的setContentView(R.layout.listplaceholder);

   新JSONPasingShowList()执行()。
}

公共无效updateWithNewLocation(位置LOCATION2){
    如果(LOCATION2!= NULL){
          双geoLat = location2.getLatitude();

            双geoLng = location2.getLongitude();

    }

}

类JSONPasingShowList扩展的AsyncTask<字符串,整数,ArrayList的< HashMap的<字符串,字符串>>>
{


  @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        mDialog =新ProgressDialog(JsonExampleActivity.this);
        mDialog.setCancelable(真正的);
        mDialog.setMessage(载入中...);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.setProgress(0);
        mDialog.show();
    }


@覆盖
受保护的ArrayList< HashMap的<字符串,字符串>> doInBackground(字符串... PARAMS){

    双纬度[] =新的双[20];
    双东经[] =新的双[20];
    字符串参考[] =新的String [20];
    双距离[] =新的双[20];
    LocationManager locationManager;
    字符串情形= Context.LOCATION_SERVICE;
    locationManager =(LocationManager)getSystemService(上下文);
    标准标准=新标准();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(假);
    criteria.setBearingRequired(假);
    criteria.setCostAllowed(真正的);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    字符串商= locationManager.getBestProvider(标准,真正的);
    位置位置= locationManager.getLastKnownLocation(供应商);

    最后LocationListener的LocationListener的=新LocationListener的(){
        公共无效onLocationChanged(位置定位){
        updateWithNewLocation(位置);
        }
        公共无效onProviderDisabled(字符串提供商){
        updateWithNewLocation(空);
        }
        公共无效onProviderEnabled(字符串提供商){}
        公共无效onStatusChanged(字符串商,INT地位,
        捆绑演员){}
        };

    updateWithNewLocation(位置);
    locationManager.requestLocationUpdates(供应商,2000,10,
            LocationListener的);


    双geoLat = location.getLatitude();
    Log.v(TAG,hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii+ geoLat);
    双geoLng = location.getLongitude();
    Log.v(TAG,hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii+ geoLng);
    ArrayList的< HashMap的<字符串,字符串>> mylist中=新的ArrayList< HashMap的<字符串,字符串>>();


    的JSONObject json=JSONFunction.getJSONfromURL("https://maps.googleapis.com/maps/api/place/search/json?location=37.422006,-122.084095&radius=1000&types=doctor&sensor=true&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

    尝试{
        JSONArray JArray = json.getJSONArray(结果);
           Log.v(TAG,取得成效);
        的for(int i = 0; I< JArray.length();我++){
            HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
            JSONObject的E = JArray.getJSONObject(我);
            JSONObject的LOCATION1 = e.getJSONObject(几何)getJSONObject(位置)。
            纬度[I] = location1.getDouble(土地增值税);
            经度[I] = location1.getDouble(LNG);
            参考文献[1] = e.getString(参考);
            Log.v(TAG,参考文献[1]);
            距离[I] = GetLatAndLng.gps2m(geoLat,geoLng,纬度[I],经度[I]);

            map.put(ID,将String.valueOf(I));
            map.put(姓名,+ e.getString(名称));
            map.put(附近,地址+ e.getString(附近)++Disance:+距离[I]);

            mylist.add(图)
        }}赶上(JSONException E){
             Log.e(log_tag,错误分析数据+ e.toString());
        }
        最终意向意图=新的意图(JsonExampleActivity.this,GetLatAndLng.class);
        叠B =新包();
        b.putStringArray(钥匙,参考);
        intent.putExtras(B);
    返回myList中;
}

 @覆盖
    保护无效onProgressUpdate(整数...值){
        super.onProgressUpdate(值);
    }

保护无效onPostExecute(ArrayList中< HashMap的<字符串,字符串>>的结果){
    mDialog.dismiss();
     ListAdapter适配器=新SimpleAdapter(JsonExampleActivity.this,结果,R.layout.listview,
             新的String [] {姓名,附近,},
             新的INT [] {R.id.item_title,R.id.item_subtitle});

 setListAdapter(适配器);
 mDialog.dismiss();
 最终的ListView LV = getListView();
 lv.setTextFilterEnabled(真正的);
 lv.setOnItemClickListener(新OnItemClickListener(){
公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
    @燮pressWarnings(未登记)
        HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getItemAtPosition(位置);
   Toast.makeText(JsonExampleActivity.this,ID+ o.get(ID)+'被点击了。,Toast.LENGTH_SHORT).show();
  最终意向意图=新的意图(JsonExampleActivity.this,GetLatAndLng.class);
   intent.putExtra(clickedid,位置);
    startActivity(意向);
    }
});
}
公共类MySimpleAdapter扩展SimpleAdapter {
     公共MySimpleAdapter(上下文的背景下,列表和LT ;?扩展地图<字符串,>>的数据,INT资源的String []从,INT []键){
        超(背景下,数据,资源,从,到);
        // TODO自动生成构造函数存根
}
}
}
}
 

这是怎么了? 在此先感谢!

解决方案

 无法建立处理程序中的线程并没有所谓的活套。prepare()
 

正在从内部doInBackground访问的东西在UI线程上。这就是不允许的。

*编辑:我看到的一切。对我来说,看起来大多是不寻常的是那些行:

  updateWithNewLocation(位置); //这是什么呢?你可以告诉我吗?
locationManager.requestLocationUpdates(供应商,2000,10,
        LocationListener的); //我不认为这是它
 

尝试将所有这些位置更新的东西到 onProgressUpdate 。我瞎在这里,因为我看不到你的code,但我的猜测的它做一些与用户界面。试试这个:

  @覆盖
保护无效onProgressUpdate(位置...位置){
    super.onProgressUpdate(值);
    updateWithNewLocation(位置);
}
 

但正如我所说,我不知道,因为我不知道是什么 updateWithNewLocation 不,除非你张贴的code在这里。

From my previous question

I was getting NullPointor exception. So i have done some changes in my code and now progress bar is showing up but getting the below errors.

11-17 23:39:51.373: ERROR/AndroidRuntime(495): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
11-17 23:39:51.373: ERROR/AndroidRuntime(495): java.lang.RuntimeException: An error occured while executing doInBackground()
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
11-17 23:39:51.373: ERROR/AndroidRuntime(495):     at java.lang.Thread.run(Thread.java:1096)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Code is...

 public class JsonExampleActivity extends ListActivity {
/** Called when the activity is first created. */
ProgressDialog mDialog;

final String TAG="a.c.b";
JSONFunction JSONfunction;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.listplaceholder);

   new JSONPasingShowList().execute();
}

public void updateWithNewLocation(Location location2) {
    if(location2!=null) {
          double geoLat = location2.getLatitude();

            double geoLng = location2.getLongitude();

    }

}

class JSONPasingShowList extends AsyncTask<String, Integer,ArrayList<HashMap<String,String>>>
{


  @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mDialog = new ProgressDialog(JsonExampleActivity.this);
        mDialog.setCancelable(true);
        mDialog.setMessage("Loading...");
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.setProgress(0);
        mDialog.show();
    }


@Override
protected ArrayList<HashMap<String,String>> doInBackground(String... params) {

    double latitude[]=new double[20];
    double longitude[]=new double[20];
    String reference[]=new String[20];
    double distance[]=new double[20];
    LocationManager locationManager;
    String context=Context.LOCATION_SERVICE;
    locationManager=(LocationManager)getSystemService(context);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);

    final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
        updateWithNewLocation(location);
        }
        public void onProviderDisabled(String provider){
        updateWithNewLocation(null);
        }
        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status,
        Bundle extras){ }
        };

    updateWithNewLocation(location);
    locationManager.requestLocationUpdates(provider, 2000, 10,
            locationListener);


    double geoLat = location.getLatitude();
    Log.v(TAG, "hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"+geoLat);
    double geoLng = location.getLongitude();
    Log.v(TAG, "hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"+geoLng);
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


    JSONObject  json=JSONFunction.getJSONfromURL("https://maps.googleapis.com/maps/api/place/search/json?location=37.422006,-122.084095&radius=1000&types=doctor&sensor=true&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

    try{
        JSONArray  JArray = json.getJSONArray("results");
           Log.v(TAG, "getting results");
        for(int i=0;i<JArray.length();i++){                     
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = JArray.getJSONObject(i);
            JSONObject location1=e.getJSONObject("geometry").getJSONObject("location");
            latitude[i]=location1.getDouble("lat");
            longitude[i]=location1.getDouble("lng");
            reference[i]=e.getString("reference");
            Log.v(TAG, reference[i]);
            distance[i]=GetLatAndLng.gps2m(geoLat, geoLng,latitude[i] ,longitude[i]); 

            map.put("id",  String.valueOf(i));
            map.put("name", "" + e.getString("name"));
            map.put("vicinity", "Address " +  e.getString("vicinity")+" "+"Disance:"+distance[i]);

            mylist.add(map);                        
        }   }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }
        final Intent intent=new Intent(JsonExampleActivity.this ,GetLatAndLng.class);
        Bundle b=new Bundle();
        b.putStringArray("key", reference);
        intent.putExtras(b);   
    return mylist;
}

 @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
    mDialog.dismiss();
     ListAdapter adapter = new SimpleAdapter(JsonExampleActivity.this, result , R.layout.listview, 
             new String[] { "name", "vicinity", }, 
             new int[] { R.id.item_title, R.id.item_subtitle });

 setListAdapter(adapter);
 mDialog.dismiss();
 final ListView lv = getListView();
 lv.setTextFilterEnabled(true); 
 lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {          
    @SuppressWarnings("unchecked")
        HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
   Toast.makeText(JsonExampleActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
  final Intent intent=new Intent(JsonExampleActivity.this ,GetLatAndLng.class);
   intent.putExtra("clickedid",position);
    startActivity(intent);
    }
});
}
public class MySimpleAdapter extends SimpleAdapter {
     public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        // TODO Auto-generated constructor stub
}
}
}
}

What is going wrong? Thanks in Advance!!!

解决方案

Can't create handler inside thread that has not called Looper.prepare()

You are accessing something on the UI thread from inside doInBackground. And that's not allowed.

*edit: I've seen everything. To me, what looks mostly unusual are those lines:

updateWithNewLocation(location); // What does this do? Could you tell me?
locationManager.requestLocationUpdates(provider, 2000, 10,
        locationListener); // I don't think this is it

Try to move all those location update stuff into the onProgressUpdate. I'm blind here since I can't see your code, but I'm guessing it does something with the UI. Try this:

@Override
protected void onProgressUpdate(Location... locations) {
    super.onProgressUpdate(values);
    updateWithNewLocation(location);
}

But as I said, I'm not sure since I can't know what updateWithNewLocation does unless you post that code here.

这篇关于在执行doInBackground异步任务时出错()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆