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

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

问题描述

来自我的上一个问题

我收到 NullPointor 异常.因此,我对代码进行了一些更改,现在显示进度条,但出现以下错误.

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()

代码是...

 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()

您正在从 doInBackground 内部访问 UI 线程上的某些内容.这是不允许的.

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

*edit:我什么都看过.对我来说,最不寻常的是那些行:

*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

尝试将所有这些位置更新内容移动到 onProgressUpdate 中.由于看不到您的代码,我在这里瞎了眼,但我猜测它对 UI 做了一些事情.试试这个:

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);
}

但正如我所说,我不确定,因为除非您在此处发布该代码,否则我无法知道 updateWithNewLocation 的作用.

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天全站免登陆