AsyncTask错误 - 无法在未调用Looper.prepare()的线程内创建处理程序

时间:2015-04-20 20:18:03

标签: android json http android-asynctask

我正在尝试发出简单的POST请求,并从网址获取回复。我使用异步任务来完成此操作,但我收到以下错误:

04-20 16:00:11.043  17340-17393/com.me.teli.c4k E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
Process: com.me.teli.c4k, PID: 17340
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.widget.Toast$TN.<init>(Toast.java:336)
        at android.widget.Toast.<init>(Toast.java:100)
        at android.widget.Toast.makeText(Toast.java:250)
        at com.me.teli.c4k.models.activity_model.CreateNewAccountWithoutFacebook$CallAsyncTask.doInBackground(CreateNewAccountWithoutFacebook.java:102)
        at com.me.teli.c4k.models.activity_model.CreateNewAccountWithoutFacebook$CallAsyncTask.doInBackground(CreateNewAccountWithoutFacebook.java:84)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)...

更奇怪的是,我在另一个项目中使用相同的代码并且它可以工作,但由于某些原因,在这个项目中它不起作用。我假设错误与在非ui线程上运行进程有关。但为什么我会收到此错误?我正在使用异步任务作为后台线程。

当我调试时,应用程序崩溃在我的Async Task

中的这一行
HttpResponse  response = httpclient.execute(httppost);

请帮忙。

这是我的代码:

public class CreateNewAccountWithoutFacebook extends ActionBarActivity {

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);                        

        ImageView saveme=(ImageView)findViewById(R.id.login_button);  
        saveme.setOnClickListener(new ImageView.OnClickListener(){

            public void onClick(View v)
            {
                try{
                    new CallAsyncTask().execute();
                }
                catch(Exception ex)
                {
                }
            }
        });

    }  

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

            @Override
            protected String doInBackground(String... arg0)
            {
                // code for checking user name and password
                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://xxxx.xxxx.xxxx.xxxx/login.php");
                    // Build The parameter
                    nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("username","jjj"));
                    nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString()));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // ERROR AT THIS LINE
                    HttpResponse  response = httpclient.execute(httppost);
                    entity = response.getEntity();
                }
                catch(Exception e1)
                {
                    Toast.makeText(getBaseContext(), "Error" + e1.toString(), Toast.LENGTH_LONG).show();
                }
                //read the responce into string
                try
                {
                    is = entity.getContent();
                    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
                    StringBuilder builder=new StringBuilder();
                    String line=null;
                    while((line=reader.readLine())!=null)
                    {
                        builder.append(line+"\n");
                    }
                    Json=builder.toString();
                    is.close();
                    reader.close();
                }
                catch(Exception e2 )
                {
                    Log.d("Buffer", "failed" + e2.toString());
                }
                // create the json object
                try
                {
                    jsonobject = new JSONObject(Json);

                    Iterator<String> iter = jsonobject.keys();
                    while (iter.hasNext()) {
                        String key = iter.next();
                        try {
                            int i=0;
                            Object value = jsonobject.get(key);
                            values.add(i, value);
                            i++;
                        } catch (JSONException e) {
                            Log.d("JsonException","error"+e.toString());
                        }
                    }
                }
                catch(Exception e3)
                {
                    Log.d("InJson","error"+e3.toString());

                }
                return null;
            }

            @Override
            protected void onPostExecute(String result)
            {
                super.onPostExecute(result);

                new AlertDialog.Builder(CreateNewAccountWithoutFacebook.this)
                        .setTitle("Login Details")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if(values.get(0).equals("Success")){
                                    Intent intent = new Intent(CreateNewAccountWithoutFacebook.this, MainActivity.class);
                                    startActivity(intent);
                                }else{
                                    password.setText("");
                                }

                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();

                progressdialog.dismiss();
            }

            @Override
            protected void onPreExecute()
            {
                super.onPreExecute();
                progressdialog=new ProgressDialog(CreateNewAccountWithoutFacebook.this);
                progressdialog.setMessage("Checking username and password please wait");
                progressdialog.show();
            }

        }
  }

0 个答案:

没有答案