如何在AsyncTask中传递字符串?

时间:2017-12-28 02:57:24

标签: java android android-asynctask

所以我在Method1内有一个像这样的网址

public void Method1 (String x) {
    String Url = "http://MYURL.com/?country=" + x + "&api_key=APIKEY";
    new AsyncTaskParseJson().execute();
}

我需要将Url传递给我的AsyncTask,如下所示

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0)  {

        try {
            // create new instance of the httpConnect class
            httpConnect jParser = new httpConnect();

            // get json string from service url
            String json = jParser.getJSONFromUrl(ServiceUrl);

            // save returned json to your test string
            jsonTest = json.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {
        textLastLocation = (TextView) findViewById(R.id.lastlocation);
        textLastLocation.setText(jsonTest);
    }
}

我需要它,因此ServiceUrl =方法中的Url。即使从查看其他人的问题和答案,我也无法弄清楚如何做到这一点

1 个答案:

答案 0 :(得分:0)

AsyncTask<First, Second, Third>上的第一个参数将定义要在execute()上传递的参数,因此您将其定义为String并传递网址。然后:

public void Method1 (String x) {
   String Url = "http://MYURL.com/?country=" + x + "&api_key=APIKEY";
   new AsyncTaskParseJson().execute(url);
}

在你的AsyncTask上,你可以在arg0 (array)上获取它,i(根据你在execute()上传递它的方式的顺序得到ndex)

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

  @Override
  protected void onPreExecute() {}

  @Override
  protected String doInBackground(String... arg0)  {
    String url = arg0[0]; // this is your passed url
    try {
        // create new instance of the httpConnect class
        httpConnect jParser = new httpConnect();

        // get json string from service url
        String json = jParser.getJSONFromUrl(ServiceUrl);

        // save returned json to your test string
        jsonTest = json.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }

  @Override
  protected void onPostExecute(String strFromDoInBg) {
    textLastLocation = (TextView) findViewById(R.id.lastlocation);
    textLastLocation.setText(jsonTest);
  }
}