我使用doinbackground()在何处使用onpostexecute()在后台做所有事情



我试图将JSON数据显示到MapView中,但始终获得空白。

我知道要填充我需要在活动中使用onpostexecute(),但是我很困惑我需要放置onpostexecute()方法,以及我需要放置哪些行。

请有人进行这些更改,在下面我编写了我的代码,这要感谢观众和读者

JSON数据: -

{
"maps": [
{
"title": "Place One",
"latitude" : "46.483742",
"longitude" : "7.663157",
"country": "Switzerland"
},
{
"title" : "Place Two",
"latitude" : "59.25235",
"longitude" : "18.465536",
"country" : "Sweden"
},
{
"title" : "Place Three",
"latitude" : "56.404182",
"longitude" : "-3.818855",
"country" : "Scotland"
}
]
}

活动代码: -

    mapOverlays = mapView.getOverlays();        
    drawable = getResources().getDrawable(R.drawable.ic_launcher);
    itemizedOverlay = new SimpleItemizedOverlay (drawable, mapView);        
    itemizedOverlay.setShowClose(false);
    itemizedOverlay.setShowDisclosure(true);
    itemizedOverlay.setSnapToCenter(false);
    class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
    HttpClient client = new DefaultHttpClient();
    // Perform a GET request for a JSON list
    HttpUriRequest request = new HttpGet("https://dl.***.com/maps.json");
    // Get the response that sends back
    HttpResponse response = null;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // Convert this response into a readable string
    String jsonString = null;
    try {
        jsonString = StreamUtils.convertToString(response.
                    getEntity().getContent());
    } catch (IllegalStateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // Create a JSON object that we can use from the String
    JSONObject json = null;
    try {
        json = new JSONObject(jsonString);
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

               try{
     JSONArray jsonArray = json.getJSONArray("maps");
     Log.e("log_tag", "Opening JSON Array ");
        for
     (int i=0;i < jsonArray.length();i++){                      

            JSONObject jsonObject = jsonArray.getJSONObject(i);
                String latitude =  jsonObject.getString("latitude");
                String longitude =  jsonObject.getString("longitude");
                String title =  jsonObject.getString("title");
                String country = jsonObject.getString("country");

                double lat = Double.parseDouble(latitude);
                double lng = Double.parseDouble(longitude);

                     Log.e("log_tag", "ADDING GEOPOINT"+title); 
                      point = new GeoPoint(
                             (int) (lat * 1E6), 
                             (int) (lng * 1E6));
                    OverlayItem overlayItem = new OverlayItem(point, title, 
                            country);
                    itemizedOverlay.addOverlay(overlayItem);
                    }
               }catch(JSONException e)        {
                 Log.e("log_tag", "Error parsing data "+e.toString());
            } 
               itemizedOverlay.populateNow(); 
               mapOverlays.add(itemizedOverlay);
                    if (savedInstanceState == null) {
        MapController controller = mapView.getController();
                        controller.setCenter(point);
                        controller.setZoom(7);
                    } else {
     // example restoring focused state of overlays
                        int focused;
                focused = savedInstanceState.getInt("focused_1", -1);
                        if (focused >= 0) {
                            itemizedOverlay.setFocus
                (itemizedOverlay.getItem(focused));
                        }
                    }
                    return jsonString;   }
     }
     }
I understand your problem, the following code is how to get the json data and showing in a listview. It is helpful for you to show when you will write the PostExecute Method. you have to set the overlay items in PostExecute method.
    package com.androidhive.jsonparsing;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    public class AndroidJSONParsingActivity extends ListActivity {
        // url to make request
        private static String url = "http://api.androidhive.info/contacts/";
        // JSON Node names
        private static final String TAG_CONTACTS = "contacts";
        private static final String TAG_ID = "id";
        private static final String TAG_NAME = "name";
        private static final String TAG_EMAIL = "email";
        private static final String TAG_ADDRESS = "address";
        private static final String TAG_GENDER = "gender";
        private static final String TAG_PHONE = "phone";
        private static final String TAG_PHONE_MOBILE = "mobile";
        private static final String TAG_PHONE_HOME = "home";
        private static final String TAG_PHONE_OFFICE = "office";
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
        // contacts JSONArray
        JSONArray contacts = null;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new GetEventsTask().execute("");
        }
        protected class GetEventsTask extends
                AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
            protected ArrayList<HashMap<String, String>> contactList;
            private final ProgressDialog dialog = new ProgressDialog(
                    AndroidJSONParsingActivity.this);
            //PreExecute Method
            protected void onPreExecute() {
                this.dialog.setMessage("Loading, Please Wait..");
                this.dialog.setCancelable(false);
                this.dialog.show();
            }
            //doInBackground Method
            @Override
            protected ArrayList<HashMap<String, String>> doInBackground(
                    String... params) {
                contactList = new ArrayList<HashMap<String, String>>();
                // Making HTTP request
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                    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();
                    json = sb.toString();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                    Log.i("json objects",""+json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
                try {
                    // Getting Array of Contacts
                    contacts = jObj.getJSONArray(TAG_CONTACTS);
                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_ADDRESS);
                        String gender = c.getString(TAG_GENDER);
                        // Phone number is agin JSON Object
                        JSONObject phone = c.getJSONObject(TAG_PHONE);
                        String mobile = phone.getString(TAG_PHONE_MOBILE);
                        String home = phone.getString(TAG_PHONE_HOME);
                        String office = phone.getString(TAG_PHONE_OFFICE);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_EMAIL, email);
                        map.put(TAG_PHONE_MOBILE, mobile);
                        // adding HashList to ArrayList
                        contactList.add(map);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return contactList;
            }
            //onPostExecute Method 

            protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
                    // selecting single ListView item
                ListView lv = getListView();
                ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
                        contactList, R.layout.list_item, new String[] { TAG_NAME,
                                TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
                                R.id.name, R.id.email, R.id.mobile });
                lv.setListAdapter(adapter);

                // Launching new screen on Selecting Single ListItem
                lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // getting values from selected ListItem
                        String name = ((TextView) view.findViewById(R.id.name))
                                .getText().toString();
                        String cost = ((TextView) view.findViewById(R.id.email))
                                .getText().toString();
                        String description = ((TextView) view
                                .findViewById(R.id.mobile)).getText().toString();
                        // Starting new intent
                        Intent in = new Intent(getApplicationContext(),
                                SingleMenuItemActivity.class);
                        in.putExtra(TAG_NAME, name);
                        in.putExtra(TAG_EMAIL, cost);
                        in.putExtra(TAG_PHONE_MOBILE, description);
                        startActivity(in);
                    }
                });
                    //Dismiss the dialog
                if (this.dialog.isShowing()) {
                    this.dialog.dismiss();
                }
            }
        }
    }

相关内容

  • 没有找到相关文章

最新更新