我已经制作了一个php文件,将数据发布到数据库并使用android我应该发布一些文本。 问题是,当我提交文本时,新数据被添加到数据库中,但它是空白数据。没有数字,文字等。
这是我的代码:
public class mainactivity extends Activity {
EditText edittext1;
EditText edittext2;
EditText edittext3;
String name;
String nationality;
String sex;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext1 = (EditText) findViewById(R.id.editText1);
edittext2 = (EditText) findViewById(R.id.editText2);
edittext3 = (EditText) findViewById(R.id.editText3);
name = edittext1.getText().toString();
sex = edittext3.getText().toString();
nationality = edittext3.getText().toString();
Button done = (Button) findViewById(R.id.button1);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread(new Runnable() {
@Override
public void run() {
DefaultHttpClient httpclient= new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.xxx.com/thescript.php");
Log.e("done 1st","its here");
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("sex", sex));
nameValuePairs.add(new BasicNameValuePair("nationality", nationality));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.e("done", String.valueOf(response));
}
catch(Exception e)
{
Log.e("didn't work", "hardluck");
e.printStackTrace();
}
}
}).start();
}
});
}
}
logcat的
09-24 20:13:50.302: E/done 1st(28390): its here
09-24 20:13:51.442: E/done(28390): org.apache.http.message.BasicHttpResponse@416c1b80
这是我当前的数据库,可能问题在于它
CREATE TABLE `people` (
`name` varchar(20) COLLATE latin1_general_ci NOT NULL,
`sex` varchar(10) COLLATE latin1_general_ci NOT NULL,
`nationality` varchar(15) COLLATE latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
答案 0 :(得分:1)
我将假设您的edittext字段用于输入,并且它正在等待用户输入。如果是这种情况,那么您可能希望在ClickListener中访问这些文本字段的值而不是create方法。
我指的是这段代码
name = edittext1.getText().toString();
sex = edittext3.getText().toString();
nationality = edittext3.getText().toString();
由于您正在onCreate上检索这些值,因此尚未输入任何内容。用户应首先输入内容,然后按下按钮并启动ClickListener。因此,您应该在ClickListener中使用上面的代码。
答案 1 :(得分:1)
您可以在onCreate方法中定义姓名,性别,国籍(当您的文本字段为空时),尝试在您的按钮监听器中执行此操作:
..........
name = edittext1.getText().toString();
sex = edittext3.getText().toString();
nationality = edittext3.getText().toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("sex", sex));
nameValuePairs.add(new BasicNameValuePair("nationality", nationality));
...........