我正在嘗試訪問遠程服務器上的數據庫。數據庫是好的,因爲它可以很好地使用php代碼,但是當我嘗試使用android應用程序在該數據庫中添加數據時,數據不會插入到數據庫中。 我已經基本遵循以下教程用於此目的將Android應用程序連接到遠程服務器上的數據庫
https://www.youtube.com/watch?v=WgOSIEWOXbQ
有以下的應用2個活動
- 主要活動(發射活動)
包含一個按鈕「添加聯繫人」,點擊「添加信息」活動即會打開。 - Add Info Activity
包含3個編輯文本和一個按鈕'保存數據',點擊'saveInfo'方法調用。
公共類ADDINFO延伸活動{
EditText editTextName, editTextEmail, editTextMobile;
String strName, strEmail, strMobile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_info_layout);
editTextName = (EditText)findViewById(R.id.editTextName);
editTextEmail = (EditText)findViewById(R.id.editTextEmail);
editTextMobile = (EditText)findViewById(R.id.editTextMobile);
}
public void saveInfo (View view)
{
strName = editTextName.getText().toString();
strEmail = editTextEmail.getText().toString();
strMobile = editTextMobile.getText().toString();
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute(strName, strEmail, strMobile);
finish();
}
class BackgroundTask extends AsyncTask<String,Void,String>
{
String add_info_url;
@Override
protected void onPreExecute() {
add_info_url = "sisuol.move.pk/add_info.php";
}
@Override
protected String doInBackground(String... params) {
String name, email, mobile;
name = params[0];
email = params[1];
mobile = params[2];
try
{
URL url = new URL(add_info_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data_string = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"+
URLEncoder.encode("mobile","UTF-8")+"="+URLEncoder.encode(mobile, "UTF-8");
bufferedWriter.write(data_string);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
return "One row of data inserted!";
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
我會根據您的建議採取行動。讓我們看看發生了什麼。謝謝 :) –