Aller au contenu

Lecture de données d'une base de données MySQL avec JSON


Recommended Posts

Bonjour, 

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;
 
@[member=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
             * */
            @[member=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 ! 

Merci d'avance ! icon_smile.gif

Lien vers le commentaire
Partager sur d’autres sites

Rejoignez la conversation

Vous pouvez poster maintenant et vous enregistrez plus tard. Si vous avez un compte, connectez-vous maintenant pour poster.

Invité
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Répondre à ce sujet…

×   Collé en tant que texte enrichi.   Coller en tant que texte brut à la place

  Seulement 75 émoticônes maximum sont autorisées.

×   Votre lien a été automatiquement intégré.   Afficher plutôt comme un lien

×   Votre contenu précédent a été rétabli.   Vider l’éditeur

×   Vous ne pouvez pas directement coller des images. Envoyez-les depuis votre ordinateur ou insérez-les depuis une URL.

×
×
  • Créer...