如何在AsyncTask中传递字符串?

问题描述 投票:0回答:1

所以我在Method1中有一个像这样的URL

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。通过查看其他人的问题和答案,我无法弄清楚如何做到这一点

java android android-asynctask
1个回答
0
投票

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

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

在你的AsyncTask上,你可以在arg0 (array)上获取它,i(ndex基于你在execute()上传递它的顺序)

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);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.