无法将数据从android应用程序发送到PHP网页(错误:不幸的是,应用程序停止工作)


Unnable to send data from android application to PHP webpage (error:Unfortunately application stopped working)

你好,我想使用Httppost将android应用程序中的字符串发布到PHP网站。应用程序布局由一个文本框和一个发送按钮组成。当我单击发送按钮时,应用程序崩溃,并显示一条消息。不幸的是,应用程序停止工作。请任何机构提供如何解决问题。

主活动.java文件

 package com.example.test5;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    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 com.example.test5.R;
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends Activity {
         Button sendButton;
            EditText msgTextField;
            /** Called when the activity is first created. */
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);       
                // make message text field object
                msgTextField = (EditText) findViewById(R.id.msgTextField);
                // make send button object
                sendButton = (Button) findViewById(R.id.sendButton);
            }
            // this is the function that gets called when you click the button
            public void send(View v)
            {
                // get the message from the message text box
                String msg = msgTextField.getText().toString();  
                // make sure the fields are not empty
                if (msg.length()>0)
                   {
                   HttpClient httpclient = new DefaultHttpClient();
                  HttpPost httppost = new HttpPost("http://thawide.com/androidtest.php");
                   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                   nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                   nameValuePairs.add(new BasicNameValuePair("message", msg));
                   try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                   try {
                    httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  msgTextField.setText(""); // clear text box
                Toast.makeText(getBaseContext(),"sucess",Toast.LENGTH_SHORT).show();

                }
                else
                {
                    // display message if text fields are empty
                    Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }
    }

Menifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test5"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET">
    </uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.test5.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

activity_main.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/msgTextField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/sendButton"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="59dp"
        android:ems="10" />
    <Button
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/msgTextField"
        android:layout_marginTop="72dp"
        android:onClick="send"
        android:text="Send" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/msgTextField"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="60dp"
        android:text="Message" />

</RelativeLayout>

服务器端代码

<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"]; 
// specify the file where we will save the contents of the variable message
$filename="androidmessages.html";
// write (append) the data to the file
//file_put_contents($filename,$message."<br />",FILE_APPEND);
 $fh = fopen("androidmessages.html", "wb");
fwrite($fh, $message."<br />");
fclose($fh);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>

您不应该在UI线程上执行网络IO。您需要使用AsyncTaskThread在后台线程上执行网络事务。

您可以参考本教程以获得更多了解。

用try-catch块包围HttpClient,并将堆栈跟踪放在此处。。您可以在AsyncTask中执行所有Internet请求,该任务使用起来非常简单,不在UI线程中处理。