Android et base de donné externe

jasminejas - 3 mars 2016 à 13:34
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 - 9 mars 2016 à 15:46
bonjour

je suis entrain de développer une application android avec une base de données externe ,alors pour l'instant j'ai réussi a établir la connexion vers le serveur firbird et je peut aussi récupérer des données de ma base , mon souci alors c'est comment insérer des données dans mon application et les envoyer à la base (je dois faire des commande client et ajouter des client de android et sera ajouter a la base ) svp j'ai bcp essayer aider moi c'est important

5 réponses

BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 103
3 mars 2016 à 13:58
Hello,

Tu dois séparer ton code:
- une partie serveur (PHP ou autre) qui fera le lien avec ta bdd et qui exposera des webservices
- une appli Android qui utilisera ces webservices pour récupérer et mettre à jour ces données
0
oui j'ai bien séparer les deux partie j travaille avec php donc comme j'ai dis avant pour la récupération s marche très bien , pour cela je suis sur que la connexion est bien établie ,voila le code php pour insérer mais je sais pas pour se qui est coté android

 
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['NAME']) && isset($_POST['PRICE']) && isset($_POST['DESCRIPTION'])) {

$name = $_POST['NAME'];
$price = $_POST['PRICE'];
$description = $_POST['DESCRIPTION'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = ibase_query("INSERT INTO products(NAME, PRICE, DESCRIPTION) VALUES('$NAME', '$PRICE', '$DESCRIPTION')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product 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);
}
?>
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 103 > jasminejas
3 mars 2016 à 16:52
Tu utilises quoi comme client HTTP sur Android?
Pour envoyer des infos, il faut que tu utilises une requête POST, un peu comme ceci:

URL url = new URL("http://serveradress.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("NAME", name)
        .appendQueryParameter("PRICE", price)
        .appendQueryParameter("DESCRIPTION", description);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();
0
oui j utilise php pour recuperer et s marché , mais je veux orientation pour insérer je ss bloqué
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 103
3 mars 2016 à 14:34
Tu bloques sur quoi?
- la partie "envoi de données" sur Android?
- la partie "réception de données" en PHP?
- la partie "stockage de données" en bdd (sql?) ?
0
bonjour et merci de me repondre : pour l'anvoie de données de client android vers mon serveur distant j'ai crée le code php suivant


// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['NAME']) && isset($_POST['PRICE']) && isset($_POST['DESCRIPTION'])) {

$name = $_POST['NAME'];
$price = $_POST['PRICE'];
$description = $_POST['DESCRIPTION'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = ibase_query("INSERT INTO products(NAME, PRICE, DESCRIPTION) VALUES('$NAME', '$PRICE', '$DESCRIPTION')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product 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);
}
?>


je sais pas si il est le bon code pour l'insertion dans la base , et d'un coté je sais pas comment écrire le code java sous android
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 103 > jasminejas
7 mars 2016 à 09:20
Attention à garder un peu de cohérence sur ce fil de discussion...
As-tu vu ma réponse ici: http://codes-sources.commentcamarche.net/forum/affich-10061379-android-et-base-de-donne-externe#5 ?

Merci de cliquer sur "Répondre au sujet" plutôt que "répondre"
0
oui j'ai vu le code que vous m avez montré mai s marche toujours pas , et aprés bcp d'essai j'ai decidé de voire quelque exemple sur le net et des tuto et voici le lien de toturiel que j'ai essyé http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

lz code pour inserer apré qlq modification et le suivant




package riro15.exemple_web_service;

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;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class AjouterClient extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.8.16/createPRODUCT.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";

public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ajouterclient);
// Edit Text
inputName = (EditText) findViewById(R.id.btnname); inputPrice = (EditText) findViewById(R.id.btnprice); inputDesc = (EditText) findViewById(R.id.btnprice);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnvalider);
// button click event btnCreateProduct.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View view) {
// creating new product in background thread new CreateNewProduct().execute();
}
});
}

//Background Async Task to Create new product
class CreateNewProduct extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() { super.onPreExecute();
pDialog = new ProgressDialog(AjouterClient.this); pDialog.setMessage("Creating Product.."); pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show();
}

//Creating product
protected String doInBackground(String... args) { String name = inputName.getText().toString();
String price = inputPrice.getText().toString(); String description = inputDesc.getText().toString();
// Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("NAME", name)); params.add(new BasicNameValuePair("PRICE", price)); params.add(new BasicNameValuePair("DESCRIPTION", description));
// getting JSON Object
// Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_product, "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(), Afficher_listCL.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();
}
}
}



et mon logcat me donne les erreur suivantes




03-09 13:49:15.309 542-555/riro15.exemple_web_service E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-09 13:49:15.329 542-555/riro15.exemple_web_service W/dalvikvm﹕ threadid=10: thread exiting with uncaught exception (group=0x40015560)
03-09 13:49:15.519 542-555/riro15.exemple_web_service E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.NullPointerException
at riro15.exemple_web_service.AjouterClient$CreateNewProduct.doInBackground(AjouterClient.java:101)
at riro15.exemple_web_service.AjouterClient$CreateNewProduct.doInBackground(AjouterClient.java:66)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
            at java.lang.Thread.run(Thread.java:1019)
03-09 13:49:20.069 542-542/riro15.exemple_web_service E/WindowManager﹕ Activity riro15.exemple_web_service.AjouterClient has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4054e290 that was originally added here
android.view.WindowLeaked: Activity riro15.exemple_web_service.AjouterClient has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4054e290 that was originally added here
at android.view.ViewRoot.<init>(ViewRoot.java:258)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at riro15.exemple_web_service.AjouterClient$CreateNewProduct.onPreExecute(AjouterClient.java:78)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at riro15.exemple_web_service.AjouterClient$1.onClick(AjouterClient.java:58)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
03-09 13:54:17.729 558-558/riro15.exemple_web_service W/ResourceType﹕ Entry identifier 0x119 is larger than entry count 0xab









merci a l avance
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 103
9 mars 2016 à 15:46
mai s marche toujours pas
Et? Sans contexte, et sans boule de cristal, on ne va pas pouvoir t'aider
aprés bcp d'essai j'ai decidé de voire quelque exemple sur le net et des tuto
C'est bien! Mais, avant de commencer un truc que l'on ne connait pas, on se renseigne ;)

Sans question, je vais essayer de deviner le problème... Je vois que ta 1ère ligne de ton logcat est très explicite: tu as un problème de parsing! Autrement dit, tu ne reçois pas ce que tu attends.

Essaies en debug avec breakpoint pour voir ce qu'il se passe.
0
Rejoignez-nous