我无法使用我的Android应用程序将我所需的数据发布到我的PHP网站

时间:2014-10-10 18:15:33

标签: php android

这是我的代码 按下发送按钮后,我的应用程序崩溃

公共类MainActivity扩展了ActionBarActivity {

    public void send(View v)
    {

        //get message from message box
        String  msg = msgTextField.getText().toString();

        //check whether the msg empty or not
        if(msg.length()>0) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.soshelp.site50.net/index.php");

            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                   nameValuePairs.add(new BasicNameValuePair("id", "01"));
                   nameValuePairs.add(new BasicNameValuePair("message", msg));
                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                   httpclient.execute(httppost);
                    msgTextField.setText(""); //reset the message text field
                    Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //display message if text field is empty
            Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
        }

1 个答案:

答案 0 :(得分:0)

为了正确执行,您必须将您的代码放在一个单独的线程中,对于android中的所有服务器调用都是如此:

 public void send(View v)
    {

Thread thread = new Thread()
{
    @Override
    public void run() {
        //get message from message box
        String  msg = msgTextField.getText().toString();

        //check whether the msg empty or not
        if(msg.length()>0) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.soshelp.site50.net/index.php");

            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                   nameValuePairs.add(new BasicNameValuePair("id", "01"));
                   nameValuePairs.add(new BasicNameValuePair("message", msg));
                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                   httpclient.execute(httppost);
                    msgTextField.setText(""); //reset the message text field
                    Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //display message if text field is empty
            Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
        }
    }
};

thread.start();

}