如何获取和使用onPostExecute(Async)的结果

时间:2014-02-13 19:13:18

标签: java android android-asynctask

对不起I try to learn this topicthis topic。但我无法通过这个问题。我想使用来自msg的结果并使用此结果在textview中显示。 如何获得结果并使用它。

接口类

public interface AsyncResponse {
 void processR(String output);}

这个主要课程

public class Exchange extends Activity implements AsyncResponse {

    String url = "abcd"

    public String getRatesData(String strUrl) {
        String strResult = "";
        try {
            URL url = new URL(strUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            strResult = readStream(con.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strResult;
    }

  public String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

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

      public AsyncResponse delegate = null;

      @Override
      public String doInBackground(String... urls) {
          return getRatesData(urls[0]);
      }
@Override
      public void onPostExecute(String jsonString) {
          String msg = "";

          try {
              JSONObject json = new JSONObject(jsonString);
              JSONObject val = json.getJSONObject("rates");                
            msg += String.format("%s\n", val.getString("SGD"));  // << use this result
            delegate.processR(msg);  

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



      }
  }

      GetRatesTask task = new GetRatesTask();
      @Override
        public void onCreate(Bundle savedInstanceState) 
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.exchange);  

       task.delegate = this;

            }

      void processR(String output){

          TextView txt1 = (TextView)findViewById(R.id.textView1);
          txt1.setText(output);   <<< show in this textview
      }

}

0 个答案:

没有答案