0

Hello I'm working with android android and doing some task in a async task. I want to call the async task and pass on string as a parameter. I've search google but with no luck, here is my code to call the async task

new warkah_detail().execute(id_warkah);

and here is my async task

class warkah_detail extends AsyncTask<String, String, String>
{
    @Override
    protected void onPreExecute()
    {
        pDialog = new ProgressDialog(warkah.this);
        pDialog.setMessage("Fetching Details...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args)
    {
        try
        {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id_warkah", id_warkah));
            json = jParser.makeHttpRequest(url_warkah, "POST", params);

Those code raise an error like this Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

What is the best way to pass string to async task? I will appreciate any help. Thanks.

[UPDATE] I had removed the toast, but I still not receive the correct string that pass to async task from the called. Any idea?

4

5 回答 5

4
Toast.makeText(getApplicationContext(), "ID : " + id_warkah, Toast.LENGTH_LONG).show();

Toast 需要在 UI 线程上执行。移动它onPostExcuted或使用runOnUiThread

你的Stringargs[0]。您应该阅读文档varargs

于 2013-06-17T08:49:40.457 回答
1

只需从您的 onBackground 方法中删除以下行。

Toast.makeText(getApplicationContext(), "ID : " + id_warkah, Toast.LENGTH_LONG).show();

并将其放在 onPostExecute 方法上或使用 runOnUiThread。

于 2013-06-17T08:51:18.270 回答
0

正如 blackbelt 所建议的,您正在后台线程上更新 ui。在PostExecute() 上执行。或使用 runOnUiThread

      runOnUiThread(new Runnable() //run on ui thread
      {
           public void run() 
           { 
               // update ui     
           }
      });

要使用参数,请使用它

       params.add(new BasicNameValuePair("id_warkah", args[0]));

您可以查看文档以获取更多信息

http://developer.android.com/reference/android/os/AsyncTask.html

您也可以将参数传递给 asynctask 的构造函数并使用它。

于 2013-06-17T08:51:58.397 回答
0

这是一个例子:

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

           protected String doInBackground(String... params) {
                  // You call your parameter like this
                  String someStringResult = doSomething(params[0]);
                  return someStringResult;
           }

           protected void onPostExecute(String result) {
                  doSomethingWithResult(result);
           }
     }

然后你这样称呼它:

      new DoSomethingTask().execute("string parameter");

顺便说一下,在这里阅读有关 AsyncTask 的更多信息:http: //developer.android.com/reference/android/os/AsyncTask.html

于 2013-06-17T09:31:52.893 回答
0

添加新的warkah_detail(id_warkah).execute(); 而不是 new warkah_detail().execute(id_warkah); 并编写一个构造函数来定义您的参数。

于 2013-06-17T09:05:34.330 回答