以下是在localhost服务器中向MySQl数据库发送数据的java代码。该 使用的脚本语言是php。 Php代码工作正常,当我输入值时 通过浏览器使用它。我觉得沟通有误。但我无法做到 调试它。请帮忙。
package com.example.databasetest1;
import java.io.IOException;
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 android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Button Enter;
EditText tName;
String sName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Enter = (Button) findViewById(R.id.bEnter);
tName =(EditText)findViewById(R.id.etName);
sName=tName.getText().toString();
Enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePair=new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("Name",sName));
HttpPost httpPost = new HttpPost("http://192.168.173.1/try_database/name_insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
}
/*public void insert() throws ClientProtocolException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePair=new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("Name",sName));
HttpPost httpPost = new HttpPost("http://192.168.173.1/try_database/name_insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}*/
@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;
}
}
答案 0 :(得分:1)
查看this上的developer.android.com教程。清楚地解释了如何使用类AsyncTask
执行与网络相关的操作。
你也可以看看:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
http://examples.javacodegeeks.com/android/core/os/asynctask/android-asynctask-example/
看看这个:
答案 1 :(得分:0)
您正在UI线程上执行不允许的n / w i / o。在单独的线程中执行。
答案 2 :(得分:0)
您正在Network
执行UIThread
次处理,这会在后姜饼设备中为您提供例外NetworkOnMainThreadException
。您需要将onClick
代码移至AsyncTask