用于向Android谷歌地图添加标记的异步任务被卡住了

时间:2013-12-20 17:59:02

标签: android json google-maps asynchronous

我有一张用这个启动的Android地图:

Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String breweryID = extras.getString("breweryID");

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

然后我使用异步任务将数据添加到地图中:

new AddBreweryMapMarkerJSON(this,map).execute(url);

当我运行它时,地图会弹出一个对话框以显示其加载,但对话框永远不会消失,信息也不会出现在地图上。

我的异步任务如下所示:

public class AddBreweryMapMarkerJSON extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;
    GoogleMap mapIn;

    public AddBreweryMapMarkerJSON(Context context, GoogleMap map)
    {
        c = context;
        mapIn = map;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting brewery information");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result, GoogleMap map){
        //decode json here
        try{

            Log.d("brewery", "in try");
            JSONObject o = new JSONObject(result);

            Log.d("brewery", result);


            String longitude = getLong(o);
            String latt = getLatt(o);

            double longDouble = Double.parseDouble(longitude);
            double lattDouble = Double.parseDouble(latt);

            //add marker
            mapIn.addMarker(new MarkerOptions()
                    .position(new LatLng(longDouble, lattDouble))
                    .title("Hello world"));



        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String getName(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("name");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }



    public String getIcon(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONObject("images").getString("large");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }

    public String getDescription(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("description");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }


    public String getYear(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("established");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }

    public String getLatt(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONArray("locations").getJSONObject(0).getString("latitude");

        } catch (JSONException e) {
            holder = "null";
        }



        return holder;

    }

    public String getLong(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONArray("locations").getJSONObject(0).getString("longitude");

        } catch (JSONException e) {
            holder = "null";
        }



        return holder;

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

我将通过此调用获得的示例JSON是:

{"message":"Request Successful","data":{"id":"g0jHqt","name":"Dogfish Head Craft Brewery","description":"The story of Dogfish Head began in June of 1995 when we opened Dogfish Head Brewings & Eats, the first state's first brewpub opened in the resort beach community of Rehoboth Beach, Delaware. The plan was to bring original beer, original food, and original music to the area.\r\n\r\nNot only was Dogfish Head Delaware's first brewpub, it was the smallest commercial brewery in America. Our very first batch, Shelter Pale Ale, was brewed on a system which essentially was three little kegs with propane burners underneath. Brewing 12 gallon batches of beer for a whole restaurant proved to be more than a full time job. When the doors to the pub first opened, we brewed three times a day, five days a week! The one benefit to brewing on such a small system was the ability to try out a myriad of different recipes. We quickly got bored brewing the same things over and over that's when we started adding all sorts of weird ingredients and getting kind of crazy with the beers!","website":"http:\/\/www.dogfish.com\/","established":"1995","isOrganic":"N","images":{"icon":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/g0jHqt\/upload_WaJNQt-icon.png","medium":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/g0jHqt\/upload_WaJNQt-medium.png","large":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/g0jHqt\/upload_WaJNQt-large.png"},"status":"verified","statusDisplay":"Verified","createDate":"2012-01-03 02:41:53","updateDate":"2013-08-24 13:07:38","locations":[{"id":"Mq24sa","name":"Main Brewery","streetAddress":"6 Cannery Village Center","locality":"Milton","region":"Delaware","postalCode":"19968","phone":"302-684-1000","website":"http:\/\/www.dogfish.com\/","latitude":38.770622,"longitude":-75.310893,"isPrimary":"Y","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"micro","locationTypeDisplay":"Micro Brewery","countryIsoCode":"US","yearOpened":"1995","status":"verified","statusDisplay":"Verified","createDate":"2012-01-03 02:41:53","updateDate":"2012-03-21 20:05:25","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}},{"id":"57kBD4","name":"Dogfish Head Brewings & Eats","streetAddress":"320 Rehoboth Avenue","locality":"Rehoboth Beach","region":"Delaware","postalCode":"19971","phone":"302-226-2739","website":"http:\/\/www.dogfish.com\/","hoursOfOperation":"Open 7 Days, Year Round! Open at noon for LUNCH everyday, & we serve DINNER every night!","latitude":38.715362,"longitude":-75.086898,"isPrimary":"N","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"brewpub","locationTypeDisplay":"Brewpub","countryIsoCode":"US","yearOpened":"1995","status":"verified","statusDisplay":"Verified","createDate":"2012-01-24 14:58:17","updateDate":"2012-03-21 20:05:25","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}},{"id":"hRSzMV","name":"DFH Alehouse, Gaithersburg","streetAddress":"800 West Diamond Ave.","locality":"Gaithersburg","region":"Maryland","postalCode":"20878","phone":"301-963-4847","website":"http:\/\/www.dogfishalehouse.com\/dogfish-head-alehouse-gaithersburg.html","hoursOfOperation":"Monday - Wednesday: 11:30am to 11:00pm\r\nThursday: 11:00am to 11:00pm\r\nFriday-Saturday: 11:00am to 12:00am\r\nSunday: 11:30am to 10:00pm","latitude":39.142971,"longitude":-77.215924,"isPrimary":"N","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"restaurant","locationTypeDisplay":"Restaurant\/Ale House","countryIsoCode":"US","yearOpened":"1995","status":"verified","statusDisplay":"Verified","createDate":"2012-01-24 15:01:34","updateDate":"2012-03-21 20:05:25","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}},{"id":"JlBnVw","name":"DFH Alehouse, Falls Church","streetAddress":"6220 Leesburg Pike","extendedAddress":"Seven Corners Shopping Center","locality":"Falls Church","region":"Virginia","postalCode":"22044","phone":"703-534-3342","website":"http:\/\/www.dogfishalehouse.com\/dfh-alehouse-falls-church.html","hoursOfOperation":"Monday - Thursday: 11:30am to 11:00pm\r\nFriday - Saturday: 11:30am to 12:00am\r\nSunday: 11:30 am to 10:00pm","latitude":38.870041,"longitude":-77.151446,"isPrimary":"N","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"restaurant","locationTypeDisplay":"Restaurant\/Ale House","countryIsoCode":"US","yearOpened":"1995","status":"verified","statusDisplay":"Verified","createDate":"2012-01-24 15:03:04","updateDate":"2012-03-21 20:05:25","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}},{"id":"w4ubfN","name":"DFH Alehouse, Fairfax","streetAddress":"13041 Lee Jackson Memorial Hwy","locality":"Fairfax","region":"Virginia","postalCode":"22033","phone":"703-961-1140","website":"http:\/\/www.dogfishalehouse.com\/dfh-alehouse-fairfax.html","hoursOfOperation":"Monday - Thursday: 11:30am to 11:00pm\r\nFriday - Saturday: 11:30am to 12:00am\r\nSunday: 11:30am to 10:00pm","latitude":38.880695,"longitude":-77.397333,"isPrimary":"N","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"restaurant","locationTypeDisplay":"Restaurant\/Ale House","countryIsoCode":"US","yearOpened":"1995","status":"verified","statusDisplay":"Verified","createDate":"2012-01-24 15:04:07","updateDate":"2012-03-21 20:05:25","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}}]},"status":"success"}

3 个答案:

答案 0 :(得分:2)

你的onPostExecute()方法没有被覆盖,这就是为什么它没有得到它自己的电话试试这个。

@Override    
protected void onPostExecute(String result){

        try{

            Log.d("brewery", "in try");
            JSONObject o = new JSONObject(result);

            Log.d("brewery", result);


            String longitude = getLong(o);
            String latt = getLatt(o);

            double longDouble = Double.parseDouble(longitude);
            double lattDouble = Double.parseDouble(latt);

            //add marker
            mapIn.addMarker(new MarkerOptions()
                    .position(new LatLng(longDouble, lattDouble))
                    .title("Hello world"));



        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

答案 1 :(得分:1)

你onPostExecute不是AsyncTask类的实际方法。 onPostExecute需要1个参数,因此您创建了一个永远不会被调用的方法,因为AsyncTask不知道那是什么。

您的退货类型取决于您在此处声明的内容AsyncTask<String, Void, String>

所以你的doInBackground需要有一个String

的返回类型

http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

您需要从onPostExecute中删除GoogleMap变量

答案 2 :(得分:0)

您的onPostExecute错了。其参数中的类型必须是doInBackground返回的内容。您的AsyncTask正在寻找onPostExecute(String result)