Android getWritableDatabase() 抛出 NullPointerException [英] Android getWritableDatabase() throws a NullPointerException

查看:56
本文介绍了Android getWritableDatabase() 抛出 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调用 getWritableDatabase() 时遇到问题.它正在返回一个 NullPointerException.最奇怪的是,此错误仅在我注释掉我的 android 清单中的几行代码后才开始发生.现在该项目又回到了原来的位置(我取消了对这些部分的注释,但它仍然抛出 NullPointerException).所以我检查了我的上下文并尝试了 this.getBaseContext() 和 this.getApplicationContext().

I am having trouble with my call to getWritableDatabase(). It is returning a NullPointerException. The thing that is strangest is that this error only began occurring after I commented out a couple lines of code in my android manifest. Now the project is back to where it was (I un-commented those sections and it still throws a NullPointerException). So I checked my context and tried this.getBaseContext() and this.getApplicationContext().

使用 getApplicationContext() 将其输出到 logcat:

Using getApplicationContext() puts this out to logcat:

08-12 09:24:20.042: E/AndroidRuntime(5572): FATAL EXCEPTION: main
08-12 09:24:20.042: E/AndroidRuntime(5572): java.lang.RuntimeException: Unable to instantiate service com.productivity.uptimeapp.NetService: java.lang.NullPointerException
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2395)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.app.ActivityThread.access$1600(ActivityThread.java:139)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.os.Looper.loop(Looper.java:137)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.app.ActivityThread.main(ActivityThread.java:5021)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at java.lang.reflect.Method.invoke(Method.java:511)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at dalvik.system.NativeStart.main(Native Method)
08-12 09:24:20.042: E/AndroidRuntime(5572): Caused by: java.lang.NullPointerException
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at com.productivity.uptimeapp.NetService.<init>(NetService.java:45)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at java.lang.Class.newInstanceImpl(Native Method)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at java.lang.Class.newInstance(Class.java:1319)
08-12 09:24:20.042: E/AndroidRuntime(5572):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2392)
08-12 09:24:20.042: E/AndroidRuntime(5572):     ... 10 more

使用 getBaseContext() 将其输出到 logcat:

Using getBaseContext() puts this out to logcat:

08-12 09:28:57.058: E/AndroidRuntime(5833): FATAL EXCEPTION: main
08-12 09:28:57.058: E/AndroidRuntime(5833): java.lang.RuntimeException: Unable to instantiate service com.productivity.uptimeapp.NetService: java.lang.NullPointerException
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2395)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.app.ActivityThread.access$1600(ActivityThread.java:139)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.os.Looper.loop(Looper.java:137)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.app.ActivityThread.main(ActivityThread.java:5021)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at java.lang.reflect.Method.invoke(Method.java:511)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at dalvik.system.NativeStart.main(Native Method)
08-12 09:28:57.058: E/AndroidRuntime(5833): Caused by: java.lang.NullPointerException
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at com.productivity.uptimeapp.NetService.<init>(NetService.java:46)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at java.lang.Class.newInstanceImpl(Native Method)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at java.lang.Class.newInstance(Class.java:1319)
08-12 09:28:57.058: E/AndroidRuntime(5833):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2392)
08-12 09:28:57.058: E/AndroidRuntime(5833):     ... 10 more

这是我的相关 NetService 代码.它是从我的第一个活动中调用的:

Here is my relevant NetService Code. It's called from my first Activity:

package com.productivity.uptimeapp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Service;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class NetService extends Service{

    private static final String TAG = NetService.class.getSimpleName();

    //variables for ServerGet
    ServerSocket serverSocket;
    private static Socket clientSocket;
    //server port
    private static final int PORT = 8888;
    private static InputStreamReader isReader;
    private static DataOutputStream dos;
    private static PrintWriter printWriter;
    private static BufferedReader bReader;
    private String mess;
    //...end ServerGet variables

    ServerGet myFeed;
    Client out;

    DbHelper dbHelper = new DbHelper(this.getBaseContext()); 
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    private final IBinder iBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public NetService getService() {
            // Return this instance of LocalService so clients can call public methods
            return NetService.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        //creates new AsyncTask
        myFeed = new ServerGet();
        //starts new AsyncTask
        myFeed.execute();

        return iBinder;

    }

    //ServerGet class asynchronously gets new strings
    private class ServerGet extends AsyncTask <Void, String, Integer>{
         //This contains my Server which gets messages from a client and responds accordingly   
    }
}

我在 Manifest 中注释掉的行只是为了让我进入默认主屏幕,以便我可以更改一些设置.通常,我希望这个应用程序替换 HOME 因此 android.intent.category.HOME 属性.我怀疑这是问题所在,但注释掉这三行是触发它的原因.

The lines that I commented out in my Manifest only served to get me to the default home screen so I could change some settings. Normally, I would want this app to replace HOME thus the android.intent.category.HOME attribute. I am doubtful that this is the problem but commenting out those three lines is what triggered it.

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/fullscreen">
        <service android:name="NetService" />
        <activity
            android:name="com.productivity.uptimeapp.Login"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <!-- <category android:name="android.intent.category.DEFAULT" /> -->
                <!-- <category android:name="android.intent.category.LAUNCHER" /> -->
                <!-- <category android:name="android.intent.category.HOME"/> -->            
            </intent-filter>
        </activity> 
        ...

我发帖的唯一原因是我发现的其他解决方案都不起作用.我希望我只是遗漏了一些简单的东西......提前致谢!

The only reason I'm posting is because none of the other solutions I have found are working. I hope I'm just missing something simple... Thanks in advance!

我找到了一个解决方案,它是在每次调用之前实例化 db(在我的 AsyncTask 方法中作为参数传递).这是因为我不能让 dbHelper 和 db 同时访问数据库.这很简单,但现在我有一堆实例化的 db 变量,我只想在顶部附近有一个.我可以做到吗?

I have found a solution which was to instantiate db before I called it each time (passed as an argument in my AsyncTask methods). This is because I can not have dbHelper and db accessing the database at the same time. This was a no-brainer but now I have a bunch of instantiated db variables where I'd like to only have one near the top. Can I make that work?

推荐答案

com.productivity.uptimeapp.NetService.<init>(NetService.java:45)

logcat 中的这一行表明在实例化您的类时出现问题 (<init>).

This line in the logcat suggests there's a problem instantiating your class (<init>).

在代码中,有如下成员变量初始化:

In the code, there's the following member variable initialization:

DbHelper dbHelper = new DbHelper(this.getBaseContext()); 
SQLiteDatabase db = dbHelper.getWritableDatabase();

问题就在这里.在 onCreate() 之前,您不能将类实例用作 Context.将 dbHelperdb 初始化推迟到 onCreate() 或更高版本.

The problem is there. You cannot use the class instance as Context until onCreate(). Defer your dbHelper and db initialization to onCreate() or later.

这篇关于Android getWritableDatabase() 抛出 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆