asycn thread和java.lang.runtimeexception

时间:2015-07-01 15:45:25

标签: android

我是新手连接服务器使用异步线程,我遇到以下错误:

java.lang.runtimeexception can't create handler inside.thread that has not called looper

我知道我读了SO answers但我不知道如何解决它。

我的代码目标是使用异步线程插入数据库“id”和“name”。任何帮助将不胜感激

package com.example.zproject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private EditText value;
    private Button btn;
    private ProgressBar pb;
    EditText namet;
    EditText idt;
    String name;
    String id;
    String line;
    String result;
    InputStream is;
    int code;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        namet=(EditText)findViewById(R.id.editText1);
        btn=(Button)findViewById(R.id.button1);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    public void onClick(View v) {
        // TODO Auto-generated method stub


                pb.setVisibility(View.VISIBLE);
                new MyAsyncTask().execute(name);        


    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://justedhak.comlu.com/receiver.php");

            try {
                // Add your data

                 name = namet.getText().toString();
                 id = idt.getText().toString();
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("id",id));
                nameValuePairs.add(new BasicNameValuePair("name",name));
                //nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                  is = entity.getContent();
                // Execute HTTP Post Request
                Log.d("Message", "> " + entity);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
                try
                {
                    BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
                {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                Log.e("pass 2", "connection success ");
            }
                catch(Exception e)
            {
                    Log.e("Fail 2", e.toString());
            }     


                try
                {
                        JSONObject json_data = new JSONObject(result);
                        code=(json_data.getInt("code"));

                        if(code==1)
                        {
                    Toast.makeText(getBaseContext(), "Inserted Successfully",
                        Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                     Toast.makeText(getBaseContext(), "Sorry, Try Again",
                        Toast.LENGTH_LONG).show();
                        }
                }
                catch(Exception e)
                {
                        Log.e("Fail 3", e.toString());
                }


        }

    }
}

1 个答案:

答案 0 :(得分:1)

doInbackground()正在执行postData()方法,此时不要使用Toast,主UI中的操作导致此问题,更改LogCat消息...

...
...
try
                {
                        JSONObject json_data = new JSONObject(result);
                        code=(json_data.getInt("code"));

                        if(code==1)
                        {
                    Toast.makeText(getBaseContext(), "Inserted Successfully",
                        Toast.LENGTH_SHORT).show(); //*INCORRECT
                        }
                        else
                        {
                     Toast.makeText(getBaseContext(), "Sorry, Try Again",
                        Toast.LENGTH_LONG).show();  //*INCORRECT
                        }
                }
...
...
像某些朋友建议的那样,如果你想向用户展示一些消息 您可以致电publishProgress()并在Toast中显示onProgressUpdate()