How to return data from asynctask

五迷三道 提交于 2020-01-24 19:53:28

问题


i have a class extends asynctask

private class taskMK extends AsyncTask<Void,Void,JSONObject>{
        String url;
        JSONObject json;
        public taskMK(String tr){
            this.url = tr;
        }
        @Override
        protected JSONObject doInBackground(Void... params) {
            JSONParser jsonParser = new JSONParser();
            JSONObject json = jsonParser.getJSONFromURL(url);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            this.json = result;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }
        public JSONObject getkq(){
            return this.json;
        }

    }

In activity

String url = "https://maps.googleapis.com/maps/api/place/search/json?location="+lat+"%2C"+lng+"&name=atm&radius="+bk+"&sensor=false&key=AIzaSyCxaZYo1zJ_QxuNcp5dL5P0xm5XvIJPXRw";
taskMK mk = new taskMK(url);
mk.execute();
JSONObject json = mk.getkq();

I intend to put this code in asynctask class but i get error "Can't create handler inside thread that has not called Looper.prepare()" .... Actually, I don't know how to do solved this.

    Double lat = loc.getLatitude();
    Double lng = loc.getLongitude();
    String url = "https://maps.googleapis.com/maps/api/place/search/json?location="+lat+"%2C"+lng+"&name=atm&radius="+bk+"&sensor=false&key=AIzaSyCxaZYo1zJ_QxuNcp5dL5P0xm5XvIJPXRw";

    JSONParser jsonParser = new JSONParser();
    JSONObject json = jsonParser.getJSONFromURL(url);
    marker=getResources().getDrawable(R.drawable.hoe);
    itemizedOverlay = new MarkerATM(marker, mapView);
    int i=0;
    try{
        JSONArray array_atm = json.getJSONArray("results");
        for(i=0;i<array_atm.length();i++){
            JSONObject c = array_atm.getJSONObject(i);
            String atm_name = c.getString("name");
            String atm_address = c.getString("vicinity");

            JSONObject geometry  = c.getJSONObject("geometry");
            JSONObject location = geometry.getJSONObject("location");
            String atm_lat = location.getString("lat");
            String atm_lng = location.getString("lng");

            Double _lat = Double.parseDouble(atm_lat)*1E6;
            Double _lng = Double.parseDouble(atm_lng)*1E6;

            GeoPoint myPoint = new GeoPoint(_lat.intValue(), _lng.intValue());
            OverlayItem overlayItem = new OverlayItem(myPoint, atm_name, atm_address);
            itemizedOverlay.addOverlay(overlayItem);                            
        }
    }   catch(JSONException e){
        e.printStackTrace();
    }
    mapOverlays.add(itemizedOverlay);

i want to get data from taskMK but data always return null ... how to do i solved my problem :( .. sorry i use english not good.


回答1:


Rather than using getkq() in the taskMK class you can have a setkq() in the activity class which is executing the asyncTask. So use the following:

private class taskMK extends AsyncTask<Void,Void,JSONObject>{
    String url;
    JSONObject json;
    MyActivityClassObject obj;

    public taskMK(String tr, MyActivityClassObject obj){
        this.url = tr;
        this.obj = obj;
    }
    @Override
    protected JSONObject doInBackground(Void... params) {
        JSONParser jsonParser = new JSONParser();
        JSONObject json = jsonParser.getJSONFromURL(url);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        this.obj.setkq(result);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
}

And in your activity class you can have this function:

public void setkq(JSONObject obj){
        //Add your parsing logic here
    }



回答2:


This is happening because AsyncTask is a Thread. It's going to do his things on his own and when you call JSONObject json = mk.getkq(); the AsyncTask probably won't be done with his task thus returning the null value.

Depending on what you want to do with your file, you might want to show some data that you parsed from your JSON file. If you want to change the UI in any way. You should do it in onPostExecute()




回答3:


Rather than bothering with AsyncTask, I'd use an IntentService, send an Intent with the work you want done to start it, and send an Intent back to your Activity when you're done.



来源:https://stackoverflow.com/questions/11001215/how-to-return-data-from-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!