开发者

Android - NullPointerException on getReadableDatabase()

开发者 https://www.devze.com 2023-04-06 05:26 出处:网络
I am writing an app that checks if the first value in the database matches a string. When I try to connect to the database, I get a NullPointerException. This happens on both getReadableDatabase() and

I am writing an app that checks if the first value in the database matches a string. When I try to connect to the database, I get a NullPointerException. This happens on both getReadableDatabase() and getWritableDatabase()

Here's my code:

public class DataManager extends SQLiteOpenHelper
{
    private final static String DB_TABLE = "Nums";
    private final static String COL_KEY      = "KEY";
    private final static String COL_VALUE= "VALUE";
    private static Context context;
    private ContentValues initialValues;
    private SQLiteDatabase db;
    private static DataManager dm;

    public static DataManager getInstance(Context _context)
    {
        if (dm==null)
        {dm=new DataManager(_context);}
        return dm;
    }

    private DataManager()
    {
        super(context, DB_TABLE, null, 1);
    }
    private DataManager(Context _context)
    {
        super(_context, DB_TABLE, null, 1);
        context=_context;
        initialValues = new ContentValues();
        if (db==null)
        {db=getWritableDatabase();}
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        StringBuilder Query = new StringBuilder();
        Query.append("CREATE TABLE IF NOT EXISTS ");
        Query.append(DB_TABLE);
        Query.append('(');
        Query.append(COL_KEY);
            Query.append(" TEXT PRIMARY KEY,");
        Query.append(COL_VALUE);
            Query.append(" TEXT);");
        Log.i(Constants.TAG,"CREATE STRING: "+Query.toString());
        db.execSQL(Query.toString());

        if(tableEmpty())
        {setDefault();}
    }

    /**
     * Populate the database with numbers 1->MAXNUM giving each a value of 0.
     */
    private void setDefault()
    {
        for (int i=1;i<=Constants.MAXNUM;i++)
        {
            setValue(String.valueOf(i),"0");
        }
    }

    /**
     * Method to get the values, ordered by frequency
     * @return Comma seperated 
     */
    public String[] getAllValues()
    {
        Cursor c=null;
        int counter=0;
        String[] val = new String[Constants.MAXNUM];

        try
        {
            c = getReadableDatabase().query(DB_TABLE, null,null, null, null, null, COL_VALUE);
            c.moveToFirst();
            //Ensure there is something in the database
            if(c.getCount()>0)
                {   // Make sure the cursor never goes over the edge
                    while(!c.isAfterLast())
                    {   // Append each value in order, seperated by a comma
                        val[counter++]=c.getString(1);
                        c.moveToNext();
                    }
                }
        }
        catch(SQLiteException e){
            Log.e(Constants.TAG,"getValue::SQLiteException::"+e.getMessage());
            e.printStackTrace();
        }
        finally {
            c.close();  // Tidy up
        }
        return val;
    }

    public String getValueByKey(String _key)
    {
        String val = "";
        try
        {
            Log.i(Constants.TAG,"key is: "+_key);
            Cursor c=getReadableDatabase().query(DB_TABLE,new String[]{COL_VALUE},COL_KEY + " LIKE ?",new String[]{_key},null,null,null);
            c.moveToFirst();
            if(c.getCount()>0)
                {   val = c.getString(0);   }
            c.close();
        }
        catch(SQLiteException e)
        {
            Log.e(Constants.TAG,"SQLiteException::"+e.getMessage());
            e.printStackTrace();
        }

        return val;
    }

    /**
     * Method checks to see if there are any records in the database
     * @return Boolean true if empty, false if not empty
     */
    private boolean tableEmpty()
    {
        boolean result = false;

        if(!(getValueByKey("1") == "0") )
        {
            result=true;
        }

        return  result;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {}  
}

My database has 2 columns. The left column has the key, and the right has the value. I am trying to get the value of the first record and return it. The error message is a generic NullPointerError so 开发者_开发问答I don't know much about the error, other than the fact that its to do with getReadableDatabase(). Can anyone see what I'm doing wrong?

Thanks.

EDIT: I've added the full code. Here's the stacktrace:

09-23 15:16:27.450: ERROR/AndroidRuntime(11825): FATAL EXCEPTION: main
09-23 15:16:27.450: ERROR/AndroidRuntime(11825): java.lang.NullPointerException
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.openDatabase(MyClass.java:137)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.getFrequency(MyClass.java:204)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.tableEmpty(MyClass.java:252)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.getAllValues(MyClass.java:169)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.setupNumbers(MyClass.java:48)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.MyClass.<init>(MyClass.java:38)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.eoinzy.myApp.ButtonControl.onClick(ButtonControl.java:56)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.view.View.performClick(View.java:2501)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.view.View$PerformClick.run(View.java:9107)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.os.Handler.handleCallback(Handler.java:587)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.os.Looper.loop(Looper.java:130)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at android.app.ActivityThread.main(ActivityThread.java:3835)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at java.lang.reflect.Method.invokeNative(Native Method)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at java.lang.reflect.Method.invoke(Method.java:507)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
09-23 15:16:27.450: ERROR/AndroidRuntime(11825):     at dalvik.system.NativeStart.main(Native Method)


Try this way of Coding so that you can easily Debug you Error.

Also Null Pointer comes for Lot of reason for Null values.

private Cursor cursor_value;
private DbHelper mDbHelper;
mDbHelper = new DbHelper(this);
mDbHelper.open();

 try{   
    String cursor_link_value,cursor_time_value,cursor_name_value;
    cursor_value = mDbHelper.fetch_message_values();
    Log.v("cursor_value", ""+cursor_value.getCount());
    startManagingCursor(cursor_value);
    if (cursor_value.moveToFirst()) {
    do {
        value =cursor_value.getString(cursor_value.getColumnIndex(Column_Name));
    } while (cursor_value.moveToNext());
   }
 }
 catch(Exception e){
    Log.v("Excepqqqqqqqqqqqqqqqqqqqq", ""+e);
 }

For DB :

Write your Query inside of DbHelper Class :

public Cursor fetch_message_values() {
    // TODO Auto-generated method stub
     Cursor c=mDb.rawQuery("Your Query",null);
     Log.v("Cursor Count for Draft Table", ""+c.getCount());
    return c;
  }

For Further Reference Check this link for Notepad Example for Database

0

精彩评论

暂无评论...
验证码 换一张
取 消