将字符串数据从AsyncTask的onPostExecute方法传递给其他活动

时间:2014-08-16 14:38:30

标签: android android-asynctask

我的问题是:在android编程中如何传递字符串数据,如名称,我们在AsyncTask的onPostExecute()方法中获取的地址到另一个将接收此字符串数据的活动。例如我想传递字符串名称,url我进入onPostExecute()方法然后通过dosomething()函数将这些字符串数据传输到另一个活动并启动该活动。请事先回复asap.Thanx。请解释解决方案代码。

PlaceDetailsActivity

 import org.json.JSONObject;

 import android.app.Activity;
 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.webkit.WebView;

 public class PlaceDetailsActivity extends Activity {
 WebView mWvPlaceDetails;


 ProgressDialog pDialog;



protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_place_details);

    // Getting reference to WebView ( wv_place_details ) of the layout activity_place_details
    mWvPlaceDetails = (WebView) findViewById(R.id.wv_place_details);

    mWvPlaceDetails.getSettings().setUseWideViewPort(false);

    // Getting place reference from the map
    String reference = getIntent().getStringExtra("reference");

    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?");
    sb.append("reference="+reference);
    sb.append("&sensor=true");
    sb.append("&key=AIzaSyChVcy-8fLkAq5-ZJCuNomF1lIf-Gda7s8");

    // Creating a new non-ui thread task to download Google place details
    PlacesTask placesTask = new PlacesTask();

    // Invokes the "doInBackground()" method of the class PlaceTask
    placesTask.execute(sb.toString());

};

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }

        data = sb.toString();
            br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
/** A class, to download Google Place Details */
private class PlacesTask extends AsyncTask<String, Integer, String>{

     /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(PlaceDetailsActivity.this);
        pDialog.setMessage("Loading Restaurent Details ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google place details in JSON format
        // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }
}

/** A class to parse the Google Place Details in JSON format */
private class ParserTask extends AsyncTask<String, Integer, HashMap<String,String>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected HashMap<String,String> doInBackground(String... jsonData) {

        HashMap<String, String> name = null;
        HashMap<String, String> hPlaceDetails = null;
        PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            // Start parsing Google place details in JSON format
            hPlaceDetails = placeDetailsJsonParser.parse(jObject);
            name = placeDetailsJsonParser.parse(jObject);


        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return hPlaceDetails;
        return name;//(here eclise gives error unrechable code)
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(HashMap<String,String> hPlaceDetails){



        // dismiss the dialog after getting all products
        pDialog.dismiss();

        String name = hPlaceDetails.get("name");
        String icon = hPlaceDetails.get("icon");
        String vicinity = hPlaceDetails.get("vicinity");
        String lat = hPlaceDetails.get("lat");
        String lng = hPlaceDetails.get("lng");
        String formatted_address = hPlaceDetails.get("formatted_address");
        String formatted_phone = hPlaceDetails.get("formatted_phone");
        String website = hPlaceDetails.get("website");
        String rating = hPlaceDetails.get("rating");
        String international_phone_number = hPlaceDetails.get("international_phone_number");
        String url = hPlaceDetails.get("url");





        String mimeType = "text/html";
        String encoding = "utf-8";

        String data = "<html>"+
                      "<body><img style='float:left' src="+icon+" /><h1><center>"+name+"</center></h1>" +
                      "<br style='clear:both' />" +
                      "<hr />"+
                      //"<p>Vicinity : " + vicinity + "</p>" +
                      //"<p>Location : " + lat + "," + lng + "</p>" +
                      "<p>Address : " + formatted_address + "</p>" +
                      "<p>Phone : " + formatted_phone + "</p>" +
                      "<p>Website : " + website + "</p>" +
                      "<p>Rating : " + rating + "</p>" +
                      "<p>International Phone : " + international_phone_number + "</p>" +
                      "<p>Reviews(Please Open in Web browser) : <a href='" + url + "'>" + url + "</p>" +
                      "</body></html>";

        // Setting the data in WebView
        mWvPlaceDetails.loadDataWithBaseURL("", data, mimeType, encoding, "");
    }
}


public void dosomething(View v)
{




 if (v.getId()==R.id.button2)
 {



 }
 else if (v.getId()==R.id.button3)
 {

 }

}
  }                                                                                                                                                                                                             

PlaceJSONParser类

             public class PlaceJSONParser {

       /** Receives a JSONObject and returns a list */
      public List<HashMap<String,String>> parse(JSONObject jObject){

     JSONArray jPlaces = null;
    try {
        /** Retrieves all the elements in the 'places' array */
        jPlaces = jObject.getJSONArray("results");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    /** Invoking getPlaces with the array of json object
    * where each json object represent a place
    */
    return getPlaces(jPlaces);
}

private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
    int placesCount = jPlaces.length();
    List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> place = null;

    /** Taking each place, parses and adds to list object */
    for(int i=0; i<placesCount;i++){
        try {
            /** Call getPlace with place JSON object to parse the place */
            place = getPlace((JSONObject)jPlaces.get(i));
            placesList.add(place);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return placesList;
}

/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){

    HashMap<String, String> place = new HashMap<String, String>();
    String placeName = "-NA-";
    String vicinity="-NA-";
    String latitude="";
    String longitude="";
    String reference="";

    try {
        // Extracting Place name, if available
        if(!jPlace.isNull("name")){
            placeName = jPlace.getString("name");
        }

        // Extracting Place Vicinity, if available
        if(!jPlace.isNull("vicinity")){
            vicinity = jPlace.getString("vicinity");
        }

        latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
        longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
        reference = jPlace.getString("reference");

        place.put("place_name", placeName);
        place.put("vicinity", vicinity);
        place.put("lat", latitude);
        place.put("lng", longitude);
        place.put("reference", reference);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return place;
  }
 }         

PlaceDetails类

 import java.io.Serializable;

   import com.google.api.client.util.Key;

/** Implement this class from "Serializable"
 * So that you can pass this class Object to another using Intents
   * Otherwise you can't pass to another actitivy
  * */
   public class PlaceDetails implements Serializable {

@Key
public String status;

@Key
public Place result;

@Override
public String toString() {
    if (result!=null) {
        return result.toString();
    }
    return super.toString();
 }
 }

感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

在我看来,桌面上有两种选择!

1.将您的AsyncTask类创建为Activity类中的内部类,然后您就可以访问所有超类属性。

public class MyActivity extends Activity {

    int property1;
    void method1() {

    }

    private class MyTask extents AsyncTask<Void, Void, Void> {

        @Override
        protected void onPostExecute(Void param)
            method1(...); // <-- this is method of the enclosing class
        }
    }
}

2.为AsyncTask类定义公共接口,并在onPostExecute

中调用其监听器
public class MyTask extends AsyncTask<Void, Void, Void> {

    OnTaskFinishedListener mListener;

    @Override
    protected void onPostExecute(Void param)
        if(mListener != null){
            mListenr.onFinished(...); // <-- call your callback
        } 
    }

    public void setOnTaskFinishedListener(OnTaskFinishedListener listener) {
        mListener = listener;
    }

    public interface OnTaskFinishedListener {
        public void onFinished(...);
    }

}