简体   繁体   中英

Getting a NullPointerException error trying to connect a MySQL database to android

I know there are a lot of questions asked like this but I've looked at them all and none of the answers have worked for me.

Here is my java class

public class AllBugsActivity extends ListActivity {

private ProgressDialog pDialog;

JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> bugsList;

private static String url_all_bugs = "http://10.0.2.2/FinalYearProject/FYPFinal/android_connect/get_all_bugs.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_BUGS = "bugs";
private static final String TAG_BID = "bid";
private static final String TAG_NAME = "name";

JSONArray bugs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_bugs);

    bugsList = new ArrayList<HashMap<String, String>>();

    new LoadAllBugs().execute();

    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

       @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            String bid = ((TextView) view.findViewById(R.id.bid)).getText()
                    .toString();

            Intent in = new Intent(getApplicationContext(),
                    EditBugActivity.class);
            in.putExtra(TAG_BID, bid);

            startActivityForResult(in, 100);
    }
});

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 100) {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllBugsActivity.this);
        pDialog.setMessage("Loading bugs. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(url_all_bugs, "GET", params);

        Log.d("All Bugs: ", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                bugs = json.getJSONArray(TAG_BUGS);

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

                    String id = c.getString(TAG_BID);
                    String name = c.getString(TAG_NAME);

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

                    map.put(TAG_BID, id);
                    map.put(TAG_NAME, name);

                    bugsList.add(map);
                }
            } else {
                Intent i = new Intent(getApplicationContext(),
                        NewBugActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        AllBugsActivity.this, bugsList,
                        R.layout.list_bug, new String[] { TAG_BID,
                        TAG_NAME},
                        new int[] { R.id.bid, R.id.name });
                setListAdapter(adapter);
            }
        });

    }

}

}

Heres my JSONParser class

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;

}

}

Heres the error im getting

    03-21 17:06:15.158    1266-1280/com.example.neil.fypy4 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)
     Caused by: java.lang.NullPointerException
            at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:98)
            at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:83)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)
03-21 17:06:15.511    1266-1266/com.example.neil.fypy4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-21 17:06:16.008    1266-1266/com.example.neil.fypy4 E/WindowManager﹕ Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41cd1748 that was originally added here
    android.view.WindowLeaked: Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41cd1748 that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
            at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
            at android.view.Window$LocalWindowManager.addView(Window.java:547)
            at android.app.Dialog.show(Dialog.java:277)
            at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.onPreExecute(AllBugsActivity.java:92)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
            at android.os.AsyncTask.execute(AsyncTask.java:534)
            at com.example.neil.fypy4.AllBugsActivity.onCreate(AllBugsActivity.java:50)
            at android.app.Activity.performCreate(Activity.java:5008)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

My php class

<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM bugs") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
    $response["bugs"] = array();
    while ($row = mysql_fetch_array($result)) {
        $bug = array();
        $bug["bid"] = $row["bid"];
        $bug["name"] = $row["name"];
        $bug["severity"] = $row["severity"];
        $bug["description"] = $row["description"];
        $bug["created_at"] = $row["created_at"];
        $bug["updated_at"] = $row["updated_at"];
        array_push($response["bugs"], $bug);
    }
    $response["success"] = 1;
    echo json_encode($response);
} else {
    $response["success"] = 0;
    $response["message"] = "No bugs found";
    echo json_encode($response);
}
?>

Any help would be greatly appreciated.

So in your stack trace, it'll show you line numbers: from this you can triangulate in your code where the NPE is coming from. Since you don't provide line numbers here, I'm going to take a guess that int success = json.getInt(TAG_SUCCESS); is causing the NPE. The reason is that it's the first possibly null object in doInBackground(...) --if you look at the JSONParser class, you return jObj which is a field member that is initialized to null, and only set if an error did not occur. That is, you do not check in doInBackground(...) whether JSONObject json returns null or not from = jParser.makeHttpRequest(url_all_bugs, "GET", params); instead relying on the TAG_SUCCESS . But this is a chicken and egg problem, since if it fails it can be null and there is no tag to check for success!

Anyways, my advice is to add if (json != null) before the try/catch in doInBackground(...) . You'll probably find your JSONParser class is failing to parse correctly. You can use the line numbers from the stack trace to pinpoint where the problem is coming from, or just use the debugger and step through your code execution.

On a side note, you can make public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) a static method since the variables static InputStream is = null; static JSONObject jObj = null; static String json = ""; static InputStream is = null; static JSONObject jObj = null; static String json = ""; don't need to be class scoped (and they are already static!). Just make them method scope and have a convenient static method call to parse your json.

A final comment: you don't need to call runOnUiThread(...) from onPostExecute(...) because onPostExecute(...) runs on the UI thread for every Async task. That's simply how Async task works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM