16

我在网上找到了这段代码,其中有一部分我不明白。对于 doInBackground 方法,传递的参数是String... params. 有人可以向我解释这是什么意思吗?那是什么...

public class AsyncHttpPost extends AsyncTask<String, String, String> {
    private HashMap<String, String> mData = null;// post data

    /**
     * constructor
     */
    public AsyncHttpPost(HashMap<String, String> data) {
        mData = data;
    }

    /**
     * background
     */
    @Override
    protected String doInBackground(String... params) {
        byte[] result = null;
        String str = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
        try {
            // set up post data
            ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            Iterator<String> it = mData.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
            }

            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
        }
        return str;
    }

    /**
     * on getting result
     */
    @Override
    protected void onPostExecute(String result) {
        // something...
    }
}
4

3 回答 3

21

三个点停留为vargars。您可以像访问它一样访问它String[]

如果方法将 varargs 作为参数,则可以使用 vargars 类型的多个值调用它:

public void myMethod(String... values) {}

你可以打电话myMethod("a", "b");

在 myMethodvalues[0]中等于“a”并且values[1]等于“b”。如果您有一个具有多个参数的方法,则 vargars 参数必须是最后一个:例如:

public void myMethod(int first, double second, String... values) {}
于 2013-06-29T16:59:34.690 回答
11
 doInBackground(String... params)
 // params represents a vararg.
 new AsyncHttpPost().execute(s1,s2,s3); // pass strings to doInbackground
 params[0] is the first string
 params[1]  is the second string 
 params[2]  is the third string 

http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(参数...)

异步任务的参数传递给doInBackground

于 2013-06-29T17:01:47.303 回答
7

javadocs

public static String format(String pattern,
                                Object... arguments);

最后一个参数类型后面的三个句点表示最后一个参数可以作为数组或参数序列传递。Varargs 只能用于最后的参数位置。

于 2013-06-29T17:04:36.990 回答