Android NullPointerException和GetDatabaseLocked

时间:2014-03-12 02:03:31

标签: java android sqlite singleton database-locking

我试图在方法中存储特定的列数据,并在另一个类String []中调用该方法,其中微调器将访问该数组以显示用户选择的列行,然后将其存储在另一个数据库中。

我得到了nulpointerexception,当我尝试open()数据库时,数据库被锁定。对不起听起来像一个完整的业余爱好者,相对较新的android。提前感谢您的帮助。

当我在我的主类中调用getInstance()和getCPnames()时,这是我的代码

    String[] carParks = CarParkDb.getInstance().getCpnames();

以下是我的数据库代码:

package com.example.parkangel;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CarParkDb {


    public static final String KEY_ID = "_id";
    public static final String KEY_CPNAME = "cpname";
    public static final String KEY_COST = "cost";


    private static final String DATABASE_NAME = "CPDB";
    private static final String DATABASE_TABLE = "CPTable";
    private static final int DATABASE_VERSION = 1;

    private CPDbHelper cpdbHelper;

    private Context ourContext;
    private SQLiteDatabase ourDatabase;
    private static CarParkDb instance;


    private static class CPDbHelper extends SQLiteOpenHelper{

        public CPDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }



@Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_CPNAME + " TEXT NOT NULL, " + KEY_COST + " TEXTNOT NULL);");

            db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values('1','LearningResource Center','2');");
            db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('2','ParkandRide','1');");
            db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('3','deHavilland Campus','2');");
            db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values('4','MultiStorey Building','2');");
            db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values('5','Reception','2');");

        }

        public void onOpen(final SQLiteDatabase db) {
            super.onOpen(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }
    }

        public CarParkDb (final Context c)
        {
            this.cpdbHelper= new CPDbHelper(c);
            establishDb();
            //ourContext = c;
}
        public void establishDb()
        {
            if (this.ourDatabase == null)
            {
                this.ourDatabase = this.cpdbHelper.getWritableDatabase();
            }

        }

        public CarParkDb() {
            // TODO Auto-generated constructor stub
        }
        public CarParkDb open() throws SQLException
        {
            System.out.println ("running open");
            cpdbHelper = new CPDbHelper(ourContext);
            ourDatabase = cpdbHelper.getWritableDatabase();
            return this;
        }

        public void close()
        {
            ourDatabase.close();
        }

        /*public long createEntry(String cpname, String cost){
            ContentValues cv = new ContentValues();
            cv.put(KEY_CPNAME, cpname);
            cv.put(KEY_COST, cost);
            return ourDatabase.insert(DATABASE_TABLE, null, cv);
        }*/

        public String getData() {
            // TODO Auto-generated method stub
            //open();
            String[] columns = new String[] {KEY_ID, KEY_CPNAME, KEY_COST};
            Cursor  c = ourDatabase.query(DATABASE_TABLE, columns, null,null,null, null, null);
            String result = " ";

            int iRow = c.getColumnIndexOrThrow(KEY_ID);
            int iCpname = c.getColumnIndexOrThrow(KEY_CPNAME);
            int iCost = c.getColumnIndexOrThrow(KEY_COST);

            for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
                result = result + c.getString(iRow) + " " +c.getString(iCpname) + " " + c.getString(iCost) + " " + "\n";
                c.close();
                ourDatabase.close();
            }
            return result;
        }

        public static CarParkDb getInstance()
        {
            synchronized(CarParkDb.class)
        {
            if (instance == null)
            {
                instance = new CarParkDb();
            }   
            return instance;
        }
        }

    public String[] getCpnames()
        {
            //open();
            if (ourDatabase == null) System.out.println ("is null");
            Cursor c = null;

            ArrayList<String> list = new ArrayList<String>();
            ourDatabase = cpdbHelper.getReadableDatabase();
            //SQLiteDatabase db = cpdbHelper.getReadableDatabase();
            String query = "SELECT " + KEY_CPNAME + " FROM " + DATABASE_TABLE;



            {
            c = this.ourDatabase.rawQuery(query, null);
            int iCpname = c.getColumnIndexOrThrow(KEY_CPNAME);
            if (c.moveToFirst())
                {
                    do
                    {
                    list.add(c.getString(iCpname));;
                    }           
                    while (c.moveToNext());
                }
                if (c != null && !c.isClosed())
                {
                c.close();
                ourDatabase.close();
                }
                return list.toArray(new String[]{});
            }
        }

} 

**LogCat**

    03-12 01:32:39.759: E/AndroidRuntime(4176): Caused by:java.lang.NullPointerException
    03-12 01:32:39.759: E/AndroidRuntime(4176):     

    at com.example.parkangel.CarParkDb.getCpnames(CarParkDb.java:191)
    03-12 01:32:39.759: E/AndroidRuntime(4176):     

    at com.example.parkangel.BookTicket.<init>(BookTicket.java:22)
    03-12 01:32:39.759: E/AndroidRuntime(4176):     

    at java.lang.Class.newInstanceImpl(Native Method)
    03-12 01:32:39.759: E/AndroidRuntime(4176):     

    at java.lang.Class.newInstance(Class.java:1208)

2 个答案:

答案 0 :(得分:1)

尝试使用以下代码更新getInstance()代码:

public static CarParkDb getInstance(Context c) // <-- added context as parameter
{
    synchronized(CarParkDb.class)
    {
        if (instance == null)
        {
            instance = new CarParkDb(c); // <-- used context in constructor
        }   
        return instance;
    }
}

问题似乎是你正在使用一个什么都不做的构造函数(对于CarParkDb)。你有另一个构造函数,它以Context作为参数并初始化你稍后使用的一些对象。

答案 1 :(得分:1)

数据库无法锁定。 &#34;锁定&#34; thinkg只是一个名为getDatabaseLocked()的方法中的NPE,它是由null Context在构造函数中传递给SQLiteOpenHelper引起的,getWritableDatabase()表现为getReadableDatabase() }或getDatabaseLocked()

要在ourContext中修复NPE,请确保open()中的null不是ourContext。截至目前,您从未初始化null,而且始终//ourContext = c;。取消注释构造函数中的establishDb()并将其移到Context上方,删除其他无参数构造函数,并按照Merlevede的建议传入getCpNames()

您的问题中的NPE堆栈跟踪是指您open()注释掉null并尝试在ourDatabase open()对象引用上调用方法时。一旦它被修复,取消注释getCpNames()。堆栈跟踪还表示您尝试在对象初始化阶段调用Context,例如初始化成员变量时。这可能为时过早,例如在onCreate()之前,活动不能用作onCreate()

您的代码中的其他一些内容,您可以点击下一步:

    + KEY_COST + " TEXTNOT NULL)中的
  • TEXT - 在NOTgetData()之间添加空格

  • moveToFirst()中的
  • :您正在关闭您正在访问游标的循环中的游标和数据库。在循环之后执行此操作。代码不应该编译,因为如果{{1}}返回false,则不会从非void函数返回任何内容。