无法将数据从android应用程序发送到PHP网页(错误:不幸应用程序停止工作)
您好,我想使用Httppost将我的android应用程序中的字符串发布到PHP网站。应用程序布局由一个文本框和一个发送按钮组成。当我单击发送按钮时,应用程序崩溃,并显示一条消息,不幸的是,应用程序停止工作。请任何人提供如何解决该问题的方法 MainActivity.java文件无法将数据从android应用程序发送到PHP网页(错误:不幸应用程序停止工作),php,android,http-post,Php,Android,Http Post,您好,我想使用Httppost将我的android应用程序中的字符串发布到PHP网站。应用程序布局由一个文本框和一个发送按钮组成。当我单击发送按钮时,应用程序崩溃,并显示一条消息,不幸的是,应用程序停止工作。请任何人提供如何解决该问题的方法 MainActivity.java文件 package com.example.test5; import java.io.IOException; import java.io.UnsupportedEncodingException;
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;
}
}
<?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;
?>
package com.example.test5;
导入java.io.IOException;
导入java.io.UnsupportedEncodingException;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入com.example.test5.R;
导入android.os.Bundle;
导入android.app.Activity;
导入android.view.Menu;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
按钮发送按钮;
编辑文本msgTextField;
/**在首次创建活动时调用*/
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//使消息文本字段成为对象
msgTextField=(EditText)findViewById(R.id.msgTextField);
//生成发送按钮对象
sendButton=(按钮)findViewById(R.id.sendButton);
}
//这是单击按钮时调用的函数
公共无效发送(视图五)
{
//从消息文本框中获取消息
字符串msg=msgTextField.getText().toString();
//确保字段不是空的
如果(msg.length()>0)
{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://thawide.com/androidtest.php");
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“id”,“12345”);
添加(新的BasicNameValuePair(“消息”,msg));
试一试{
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
试一试{
httpclient.execute(httppost);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
msgTextField.setText(“”;//清除文本框
Toast.makeText(getBaseContext(),“success”,Toast.LENGTH_SHORT.show();
}
其他的
{
//如果文本字段为空,则显示消息
Toast.makeText(getBaseContext(),“所有字段都是必需的”,Toast.LENGTH_SHORT.show();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回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>
活动\u 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>
服务器端代码
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;
}
}
<?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。您需要使用
AsyncTask
或Thread
在后台线程上执行网络事务
您可以参考此内容以获得更多理解。使用try-catch块环绕HttpClient,并将堆栈跟踪放在此处。。 您可以在AsyncTask中执行所有Internet请求,该任务使用起来非常简单,并且不在UI线程中处理 不要在这里发布您的全部代码。没有人会读它。学习使用调试器并了解实际问题。