我想学习如何将数据从Android应用程序发送到网络服务器。我从教程中复制了一个代码,但是当我的应用程序尝试发送数据时,它只是崩溃了。 LogCat说:FatalException:main
我还没有网络服务器来发送数据,但我不认为这是问题所在。应用程序在执行任何操作之前崩溃。在你问之前,是的,我已经授予了互联网权限。
该计划如下:
package com.example.helloworld;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
// import everything you need
import android.app.Activity;
import android.os.Bundle;
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
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// load the layout
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://yourwebsite.com/yourPhpScript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
}
这是我正在遵循的教程:
答案 0 :(得分:1)
你不能在主线程中进行任何网络互动,你应该在其他线程中进行
您可以AsyncTask
课程进行网络互动
这是AsyncTask和互联网反应的简单示例Understanding AsyncTask – Once and Forever
请参阅AsyncTask文档
注意您的应用必须具有android.permission.INTERNET
权限
答案 1 :(得分:-1)
您无法在主线程中发出Html请求。尝试asyncTask
public class AsyncDBTask extends AsyncTask<String, Void, String> {
String message;
public AsyncDBTask(String message){
this.message=message;
}
@Override
protected String doInBackground(String... params) {
rest=MySQLOperations.sendMessage(message);
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}