我试图制作一个与php文件/数据库通信的Android应用程序
我不能让它工作,我对这种Android编程完全陌生
我已经从教程中得到了这个:
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
name = userInput.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/register.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
PHP代码:
// including database connection
$name= $_POST['name'];
$register= "INSERT INTO Users (Name, Level) VALUES(".$name.", 1)";
$result = $conn->prepare($register);
$result->execute();
当我启动我的应用程序时,它会立即崩溃
我做错了什么?
这段代码是否仍然有用?
我忘记了什么吗?
答案 0 :(得分:0)
当我启动我的应用程序时,它会立即崩溃。
您应该在后台线程中调用http请求。您可以将AsyncTask用于此目的。
ostreamer
您可以使用<<
答案 1 :(得分:0)
所有数据库通信都应在后台完成。这可以通过使用AsyncTask或其他Worker来完成。您还需要Internet权限,将此行添加到清单中:
<uses-permission android:name="android.permission.INTERNET"/>
但我建议您使用像Retrofit这样的库进行API调用。这让你痛苦不堪,而且GSON的结合非常强大。
答案 2 :(得分:0)
首先,Android中的Google AsynchTask
并了解它是什么。并记住所有网络相关的操作必须在一个单独的线程中完成,而不是在主Android UI线程中完成。所以你正在尝试的代码应该是这样的
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
name = userInput.getText().toString();
new CallPostService().execute();
}
class CallPostService extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(YourActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/register.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
@Override
protected void onPostExecute(String response) {
progressDialog.dismiss();
}
请记得在manifest.xml文件中添加以下行
<uses-permission android:name="android.permission.INTERNET"/>
答案 3 :(得分:0)
检查此代码,它会对您有所帮助 https://github.com/kosalgeek/generic_asynctask