简体   繁体   English

尝试将MySQL数据库连接到android时遇到NullPointerException错误

[英]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 这是我的java课

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 这是我的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;

}

} }

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课

<?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. 因此,在堆栈跟踪中,它将显示行号:从中可以对NPE来自的代码进行三角剖分。 Since you don't provide line numbers here, I'm going to take a guess that int success = json.getInt(TAG_SUCCESS); 由于您此处未提供行号,因此我将猜测int success = json.getInt(TAG_SUCCESS); is causing the NPE. 导致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. 原因是它是doInBackground(...)的第一个可能为null的对象doInBackground(...)如果查看JSONParser类,则返回jObj ,它是初始化为null的字段成员,并且仅在未发生错误时设置。 That is, you do not check in doInBackground(...) whether JSONObject json returns null or not from = jParser.makeHttpRequest(url_all_bugs, "GET", params); 也就是说,您无需在doInBackground(...)检查JSONObject json是否从= jParser.makeHttpRequest(url_all_bugs, "GET", params);返回null = jParser.makeHttpRequest(url_all_bugs, "GET", params); instead relying on the TAG_SUCCESS . 而是依靠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! 但这是一个鸡与蛋的问题,因为如果失败,它可以为null,并且没有标签来检查成功!

Anyways, my advice is to add if (json != null) before the try/catch in doInBackground(...) . 无论如何,我的建议是在doInBackground(...)的try / catch之前添加if (json != null) doInBackground(...) You'll probably find your JSONParser class is failing to parse correctly. 您可能会发现JSONParser类无法正确解析。 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 = ""; 附带说明一下,您可以将public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)静态方法,因为变量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. 只需使它们成为方法范围,并有一个方便的静态方法调用即可解析您的json。

A final comment: you don't need to call runOnUiThread(...) from onPostExecute(...) because onPostExecute(...) runs on the UI thread for every Async task. 最后的评论:您不需要从onPostExecute(...)调用runOnUiThread(...) ,因为onPostExecute(...)在UI线程上针对每个异步任务运行。 That's simply how Async task works. 这就是异步任务的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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