将字符串数据从AsyncTask的onPostExecute方法传递给另一个Activity

时间:2014-08-15 19:28:17

标签: android android-intent android-asynctask

如何将我们在onPostExecute() AsyncTask方法中获得的名称,地址等字符串数据传递给另一个将接收此字符串数据的活动?

例如

我想传递我在onPostExecute()方法中获得的字符串名称,然后通过dosomething()函数将这些字符串数据传输到另一个活动并启动该活动。

package info.androidhive.slidingmenu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.util.HashMap;

  import org.json.JSONObject;



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> hPlaceDetails = null;
        PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();

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

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

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return hPlaceDetails;
    }

    // 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.button1)
 {

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



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

 }

}
}

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

这实际上取决于你如何实现AsyncTask。

我的假设基于你可能从第一个活动中调用task.execute();

我建议你为任务创建一个构造函数,将第一个活动的上下文作为参数。

然后,你打电话

Intent intent = new Intent(context, NewActivity.class);
intent.putString("SOME_KEY", resultString);
context.startActivity(intent);

在活动中,将其从捆绑中取出并使用它。

答案 1 :(得分:0)

您可以执行以下操作: 这将使用AsyncTask中SecondActivity中提供的所有数据启动HashMap

public class ParserTask extends AsyncTask<String, Integer, HashMap<String,String>> {

    @Override
    protected HashMap<String,String> doInBackground(Void... jsonData) {
        HashMap<String,String> data = null;
        // TODO get your data
        return data;
    }

    @Override
    protected void onPostExecute(HashMap<String,String> data) {
        super.onPostExecute(data);
        doSomething(data);
    }
}

public void doSomething(HashMap<String,String> data) {
    Intent intent = new Intent(this, SecondActivity.class);
    Bundle bundle = new Bundle();
    Set<Entry<String,String>> entrySet = data.entrySet();
    for (Entry<String, String> entry : entrySet) {
        bundle.putString(entry.getKey(), entry.getValue());
    }
    intent.putExtras(bundle);
    startActivity(intent);
}