1

大家好,新年快乐,我正在尝试从 MySQL 数据库中获取数据并将其显示在我的 android 项目的 ListView 中。

这是主要活动的代码:

MainActivity.java

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
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;
import android.widget.ListView;
import android.widget.SimpleAdapter;



public class MainActivity extends Activity {
    private ProgressDialog pDialog;
    Button BTconnect;
    EditText EDlogin;
    EditText EDmdp;
    private String login;
    private String mdp;
    private HDdb dbase; 
    private JSONParser jsonParser  = new JSONParser();
    public final static String EXTRA_MESSAGE="com.example.HDtesr.id";
    private static String KEY_SUCCESS = "success";

    private static String loginURL = "http://10.0.2.2/android_connect/identification.php";

    private static final String TAG_CMDS = "commandes";
    private static final String TAG_CLIENT = "client";
    private static final String TAG_DEMANDE = "demande";
    private static final String TAG_DATE = "date";
    private static final String TAG_TIME = "time";

    JSONArray cmds = null;
    ArrayList<HashMap<String, String>> cmdsList;
    private HashMap<String, String> map;

    private ListView lv;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BTconnect = (Button) findViewById(R.id.connect);
        EDlogin = (EditText) findViewById(R.id.login);
        EDmdp = (EditText) findViewById(R.id.mdp);
        lv = (ListView) findViewById(R.id.list);    

        BTconnect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                  login = EDlogin.getText().toString();
                  mdp = EDmdp.getText().toString();

                 new Identify().execute();

            }
        });
    }



    class Identify extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Envoi en cours...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

         protected String doInBackground(String... args) {

             List<NameValuePair> params = new ArrayList<NameValuePair>();
              params.add(new BasicNameValuePair("login", login));
              params.add(new BasicNameValuePair("mdp", mdp));
            JSONObject json = jsonParser.makeHttpRequest(loginURL,"POST", params);

             // check log cat for response
             Log.d("Create Response", json.toString());

             // check for success tag
             try {

                 int success = json.getInt(KEY_SUCCESS);

                     if(success == 1){
                         cmds = json.getJSONArray(TAG_CMDS);

                         for (int i = 0; i < cmds.length(); i++) {
                               JSONObject c = cmds.getJSONObject(i);

                               // Storing each json item in variable

                               String client = c.getString(TAG_CLIENT);
                              String demande = c.getString(TAG_DEMANDE);
                              String date = c.getString(TAG_DATE);
                               String time = c.getString(TAG_TIME); 

                              map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value

                    map.put(TAG_CLIENT, client);
                   // map.put(TAG_DEMANDE, demande);
                   map.put(TAG_DATE, date);
                    map.put(TAG_TIME, time);
                    cmdsList.add(map);


                           }



                        finish();
                     }else{
                         // Error in login

                     }

             } catch (JSONException e) {
                 e.printStackTrace();
             }



             return null;
         }

         protected void onPostExecute(String file_url) {
             // dismiss the dialog once done
             pDialog.dismiss();
             runOnUiThread(new Runnable() {
            public void run() {

         adapter = new SimpleAdapter(Commande.this,  cmdsList,R.layout.menuitem,new String[] { TAG_DEMANDE,TAG_CLIENT,TAG_TIME},
                      new int[] { R.id.demande,R.id.client,R.id.time});
                lv.setAdapter(adapter);
         }

        });

             }


         }



    }

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    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;

    }
}

LogCat 显示它收到了数据,然后显示 JAVA.NULLPOINTEREXCEPTION !

01-01 14:51:31.541: E/AndroidRuntime(660): FATAL EXCEPTION: AsyncTask #1
01-01 14:51:31.541: E/AndroidRuntime(660): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 14:51:31.541: E/AndroidRuntime(660):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 14:51:31.541: E/AndroidRuntime(660):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.lang.Thread.run(Thread.java:856)
01-01 14:51:31.541: E/AndroidRuntime(660): Caused by: java.lang.NullPointerException
01-01 14:51:31.541: E/AndroidRuntime(660):  at com.example.hd_test.MainActivity$Identify.doInBackground(MainActivity.java:95)
01-01 14:51:31.541: E/AndroidRuntime(660):  at com.example.hd_test.MainActivity$Identify.doInBackground(MainActivity.java:1)
01-01 14:51:31.541: E/AndroidRuntime(660):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-01 14:51:31.541: E/AndroidRuntime(660):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-01 14:51:31.541: E/AndroidRuntime(660):  ... 5 more
4

0 回答 0