将参数传递给异步类,使param [0]和params [1]包含不同的值

时间:2016-08-12 08:32:33

标签: java android

我正在开发一款适合天气的Android应用。我将邮政编码作为输入传递给异步任务类。但是我想要传递国家代码。

     @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        FetchWeatherTask weatherTask = new FetchWeatherTask();
        weatherTask.execute("110087"); //THE ARGUMENT I PAASED IS POSTAL CODE

        return true;
    }
    return super.onOptionsItemSelected(item);
}

我也希望传递国家/地区代码(例如IN),这样当我构建我的uri时,它就会有邮政编码,IN

示例:

http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&APPID=74250c25b0f8a52f176e6d6e3717e285

如果我包含国家/地区代码,则应为:

http://api.openweathermap.org/data/2.5/forecast/daily?q=94043,IN&mode=json&units=metric&cnt=7&APPID=74250c25b0f8a52f176e6d6e3717e285

代码:

String format = "json";
String units = "metric";
int numDays = 7;

try {
    // Construct the URL for the OpenWeatherMap query
    // Possible parameters are avaiable at OWM's forecast API page, at
    // http://openweathermap.org/API#forecast
    final String FORECAST_BASE_URL =
                    "http://api.openweathermap.org/data/2.5/forecast/daily?";
    final String QUERY_PARAM = "q";
    final String FORMAT_PARAM = "mode";
    final String UNITS_PARAM = "units";
    final String DAYS_PARAM = "cnt";
    final String APPID_PARAM = "APPID";

    Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM, params[0])
                    .appendQueryParameter(FORMAT_PARAM, format)
                    .appendQueryParameter(UNITS_PARAM, units)
                    .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                    .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
                    .build();

    URL url = new URL(builtUri.toString());

    Log.v(LOG_TAG, "Built URI " + builtUri.toString());

简单的解决方案是通过:

weatherTask.execute("110087IN");

但是我想在uri构建中添加查询,并且我想将2个实体传递给类,这样就像params [0]一样" 110087"所以params [1]应该是" IN"。

我希望你理解这个问题

2 个答案:

答案 0 :(得分:3)

execute()的{​​{1}}方法可以接受多个参数。如果你需要传递更多的参数,你就这样做:

AsyncTask

然后weatherTask.execute("110087", "IN") params[0]"110087"params[1]

答案 1 :(得分:2)

像这样更改AsyncTask

private class FetchWeatherTask extends AsyncTask<Object, Void, Void> {

    @Override
    protected void doInBackground(Object... params) {

        String postalCode = (String) params[0];
        String countryCode = (String) params[1];
        // if you also want to pass third value in type int it should be like
        //int thirdValue = (Integer) params[3]
    }
    ...
}

然后,您可以将具有不同类型的多个值传递到AsyncTask

weatherTask.execute("110087", "IN")