Novice en programmation Android, je cherche à lire des données sur une base de données externes MySQL, mais j'ai une erreur lors de la lecture de celles-ci..
J'ai cette erreur dans le logcat :
05-25 09:31:59.107 2325-4890/com.example.petotmarc.cftcfranche_comte E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: com.example.petotmarc.cftcfranche_comte, PID: 2325 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at com.example.petotmarc.cftcfranche_comte.ArticleActivity$LoadAllArticles.doInBackground(ArticleActivity.java:145) at com.example.petotmarc.cftcfranche_comte.ArticleActivity$LoadAllArticles.doInBackground(ArticleActivity.java:120) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818)
Voici mon code :
public class ArticleActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> articlesList;
// url to get all products list
private static String url_all_article = "http://10.0.2.2/GestionArticle/getAllArticle.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "idArticle";
private static final String TAG_TITRE = "titre";
private static final String TAG_DATEARTICLE = "dateArticle";
private static final String TAG_HEUREARTICLE = "heureArticle";
// products JSONArray
JSONArray articles = null;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
//Hashmap for ListView
articlesList = new ArrayList<HashMap<String, String>>();
new LoadAllArticles().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllArticles extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ArticleActivity.this);
pDialog.setMessage("Chargement des articles. Attendez s'il vous plaît...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_article, "GET", params);
// Check your log cat for JSON reponse
Log.d("Tous les articles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of articles
articles = json.getJSONArray(TAG_ARTICLES);
// looping through All articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String titre = c.getString(TAG_TITRE);
String dateArticle = c.getString(TAG_DATEARTICLE);
String heureArticle = c.getString(TAG_HEUREARTICLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITRE, titre);
map.put(TAG_DATEARTICLE, dateArticle);
map.put(TAG_HEUREARTICLE, heureArticle);
// adding HashList to ArrayList
articlesList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
//Afficher "Erreur, pas d'articles"
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
Ainsi que mon code php pour interagir avec la base :
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get a product from products table
$result = mysql_query("SELECT idArticle, titre, dateArticle, heureArticle FROM article ORDER BY idArticle DESC");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$article = array();
$article["idArticle"] = $result["idArticle"];
$article["titre"] = $result["titre"];
$article["dateArticle"] = $result["dateArticle"];
$article["heureArticle"] = $result["heureArticle"];
// success
$response["success"] = 1;
// user node
$response["article"] = array();
array_push($response["article"], $article);
// echoing JSON response
echo json_encode($response);
} else {
// no article found
$response["success"] = 0;
$response["message"] = "No article found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no article found
$response["success"] = 0;
$response["message"] = "No article found";
// echo no users JSON
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);
}
Donc voilà, si quelqu'un peut m'aider à résoudre ce problème, je lui en serais très reconnaissant !
Salut. Met ton adresse ip locale a la place de 10.0.2.2 ( du style 192.168..... ).
L'erreur te dit tout simplement que ton objet json est null donc il récupère rien depuis ton serveur dans ce cas. Change d'adresse pour commencer et tiens nous au courant.
Ps: Au passage, les fonctions mysql_ ont été supprimée dans la version 7 de php donc pense à passer sur mysqli ou pdo côté php ;).
L'erreur étant assez explicite et maintenant comprise : "Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference" . Tu essaie d'invoquer la méthode ToString sur un objet null et ça n'est bien évidemment pas possible.
On repère où se produit l'erreur : Ligne 69 est la premiere fois qu'on appel toString();
Log.d("Tous les articles: ", json.toString());
Étape 3 (ou 0 si on est plus rapide) :
On utilise le debuguer et on met un point d'arrêt a la ligne 66 par exemple
On regarde la valeur du JSONObject json et on remarque qu'il est null.
Étape 4 :
On a maintenant identifier le problème.
Maintenant pourquoi est-il null ?
Il peut y avoir plusieurs raisons a tout cela :
Les données renvoyés par la page web sont mauvaises
Tu n'arrive pas ou ne sait pas comment requêter ta page.
As tu activer les permissions d'accès a internet dans ton manifest ?
Bon courage.
Ps : Les fonctions mysql_* sont a bannir ( obsolète depuis PHP5) et à remplacer par PDO ou mysqli
PPs : Je te recommande d'utiliser cette librairie simple d'utilisation pour débutant : AsyncHttpClient .
Mon problème vient donc sûrement du fait que j'arrive pas à requêter ma page je pense, et c'est pour cela que je sollicite vos aides car j'ai compris l'erreur mais je ne sais pas comment la résoudre..
J'ai essayé en changeant d'adresse, mais j'ai la même erreur qui survient..
J'ai oublié de copier cette ligne du logcat au tout début:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
Non du coup c'est plus la même erreur. La tu reçois bien une réponse mais elle est mal formatée et ça te renvoie une JSONException.
Ca ressemble plus à une erreur côté php. Quand tu vas sur la page que t'essayes d'appeler, ça t'affiches bien ce que tu souhaites ? Et normalement tu devrais désormais avoir la réponse qui s'affiche dans le log et donc voir a quoi ressemble la réponse ( et la te verrais que tu reçois un truc pas normal ;))
En effet, mon fichier php n'est pas bon... Je n'avais pas vérifié, j'ai corrigé le else en trop, j'ai un erreur au niveau du require_once, je vais essayer de corriger ce problème !
Edit :
Donc j'ai corrigé ma page php, quand je l'execute, ça affiche bien ce que je veux, mais j'ai toujours la même erreur dans l'application ..
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.petotmarc.cftcfranche_comte.ArticleActivity$LoadAllArticles.doInBackground(ArticleActivity.java:147)
at com.example.petotmarc.cftcfranche_comte.ArticleActivity$LoadAllArticles.doInBackground(ArticleActivity.java:122)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Et le code actuel :
public class ArticleActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> articlesList;
// url to get all products list
private static String url_all_article = "http://192.168.x.x/GestionArticle/getAllArticle.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "idArticle";
private static final String TAG_TITRE = "titre";
private static final String TAG_DATEARTICLE = "dateArticle";
private static final String TAG_HEUREARTICLE = "heureArticle";
// products JSONArray
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
//Hashmap for ListView
articlesList = new ArrayList<HashMap<String, String>>();
new LoadAllArticles().execute();
// Get listview
ListView lv = getListView();
//ListView lv = (ListView)findViewById(R.id.list);
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String idArticle = ((TextView) view.findViewById(R.id.idArticle)).getText()
.toString();
// Starting new intent
//Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
//in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
//startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllArticles extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ArticleActivity.this);
pDialog.setMessage("Chargement des articles. Attendez s'il vous plaît...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All articles from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_article, "GET", params);
// Check your log cat for JSON reponse
Log.d("Tous les articles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
articles = json.getJSONArray(TAG_ARTICLES);
// looping through All Products
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String titre = c.getString(TAG_TITRE);
String dateArticle = c.getString(TAG_DATEARTICLE);
String heureArticle = c.getString(TAG_HEUREARTICLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITRE, titre);
map.put(TAG_DATEARTICLE, dateArticle);
map.put(TAG_HEUREARTICLE, heureArticle);
// adding HashList to ArrayList
articlesList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
//Afficher "Erreur, pas d'articles"
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
avec la classe JSONParser :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
at miui.cloud.finddevice.FindDeviceStatusManagerProvider.isLastStatusOpen(FindDeviceStatusManagerProvider.java:29)
at com.miui.cloudservice.finddevice.FindDeviceGuidePeriodicNotification.update(FindDeviceGuidePeriodicNotification.java:32)
at com.miui.cloudservice.CloudApp$DelayedInitializer.doInBackground(CloudApp.java:108)
at com.miui.cloudservice.CloudApp$DelayedInitializer.doInBackground(CloudApp.java:97)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
Avant de poster un message, vérifiez la date du sujet dans lequel vous comptiez intervenir.
Si le dernier message sur le sujet date de plus de deux mois, mieux vaut ne pas répondre. En effet, le déterrage d'un sujet nuit au bon fonctionnement du forum, et l'informatique pouvant grandement changer en quelques mois il n'est donc que rarement pertinent de déterrer un vieux sujet.
Au lieu de déterrer un sujet il est préférable :
soit de contacter directement le membre voulu par messagerie privée en cliquant sur son pseudonyme pour accéder à sa page profil, puis sur le lien "Ecrire un message"
soit de créer un nouveau sujet décrivant votre propre contexte
ne pas répondre à un déterrage et le signaler à la modération
Pas d'aide concernant le code par MP, le forum est là pour ça :)