2

我是 android 新手,如何将值从 android 插入到 php mysql 我尝试了以下代码,它没有显示任何错误但无法正常工作。谁能帮我。谁能纠正我的错误。

public class MainActivity extends Activity{

    EditText username, email, password;
    Button btn;
    HttpResponse response;

    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        username = (EditText) findViewById(R.id.usr_name);
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);

        btn = (Button) findViewById(R.id.regbtn);
        btn.setOnClickListener(new View.OnClickListener(){


            public void onClick(View v){

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/androidtest.php");

                try{

                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("uname", username.toString()));
                    nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    response = httpclient.execute(httppost);

                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

}
4

2 回答 2

0

我在本地 VM 上测试了您的示例,对我来说,正如我之前评论的那样, “06-01 00:22:17.671: W/System.err(2024): android.os.NetworkOnMainThreadException” 。

不要在主线程上进行联网。

关于如何使用异步任务的(其他)示例是 postet here

异步任务与主线程并行执行,因此它们不会阻塞主线程。阻塞主线程是不好的,因为它例如阻止用户界面重新绘制/界面无法处理输入。
Therfore android 抛出一个 NetworkOnMainThreadException 来阻止你在主线程上做网络(一个耗时的任务)。

可以在此处找到示例实现。

于 2013-06-01T00:23:58.590 回答
0

它可能不起作用,因为您试图将消息发送到 mainUI 线程上的 php。尝试将您的代码放入这样的异步任务中

class Task extends AsyncTask<Void, Void, Void>{

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


    HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/androidtest.php");

            try{

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("uname", username.toString()));
                nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = httpclient.execute(httppost);

            }catch(Exception e){
                e.printStackTrace();
            }
    }
}

然后像这样称呼它

new Task().execute();
于 2013-06-01T00:26:00.067 回答