J'avais téléchargé un code pour le développement de l'application Android connecté avec mysql et php pour apprendre. d'ici: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ J'ai essayé de faire les mêmes démarches pour plus de compréhension. J'ai créé une deuxième table (test) dans la même base de données .. et j'ai écrit le code PHP pour créer une nouvelle première dans la (table de test) .. Voici le code php:connecter l'application android avec mysql
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['age'])){
$name = $_POST['name'];
$age = $_POST['age'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO test (name, age) VALUES('$name', '$age')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "row successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
après que j'ai ajouté une classe java dans le projet Eclipse, suivant le code:
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewRowActivity extends Activity{
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputAge;
// url to create new row
private static String url_create_raw = "http://10.0.2.2/test/create_row.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_raw);
// Edit Text
inputName = (EditText) findViewById(R.id.editTextName);
inputAge = (EditText) findViewById(R.id.editTextAge);
// Create button
Button btnAddRow = (Button) findViewById(R.id.buttonAdd);
// button click event
btnAddRow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewRow().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewRow extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewRowActivity.this);
pDialog.setMessage("Adding a raw ..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Adding raw
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String age = inputAge.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("age", age));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_raw,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainScreenActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Lorsque l'application est en cours d'exécution dans l'émulateur, il ne fonctionne pas! Et l'émulateur s'est arrêté.
Une solution?
post journal également lorsque l'application plante et également déplacer tout le code lié à l'interface utilisateur de 'doInBackground' à' onPostExecute' –