从数据库中获取数据时,SQLite的问题 [英] SQLite problems when getting data from the database

查看:143
本文介绍了从数据库中获取数据时,SQLite的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库处理器类是这样的:

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "CaseDatabase";
private static final String TABLE_CASES = "cases";
private static final String KEY_ID = "id";
private static final String DATE = "date";
private static final String RIGHTFINGER = "rightFinger";
private static final String LEFTFINGER = "leftFinger";


public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

      String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CASES + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + DATE + " TEXT,"
                + RIGHTFINGER + " BLOB," + LEFTFINGER +" BLOB" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);

}

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

      db.execSQL("DROP TABLE IF EXISTS " + TABLE_CASES);

        // Create tables again
        onCreate(db);

}

public void addContact(Case c) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, c.getCaseNumber()); // PCN
    values.put(DATE, c.getDate()); // Date

    ByteArrayOutputStream out1 = new ByteArrayOutputStream();
    c.getLeftIndexFinger().compress(Bitmap.CompressFormat.PNG, 100, out1); 

    ByteArrayOutputStream out2 = new ByteArrayOutputStream();
    c.getRightIndexFinger().compress(Bitmap.CompressFormat.PNG, 100, out2); 

    values.put(LEFTFINGER, out1.toByteArray()); // LFINGER
    values.put("RIGHTFINGER", out2.toByteArray()); //RFINGER



    // Inserting Row
    db.insert(TABLE_CASES, null, values);
    db.close(); // Closing database connection
}

public ArrayList<Case> getAllContacts() {
    ArrayList<Case> caseList = new ArrayList<Case>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CASES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Case c = new Case();

            c.setCaseNumber(cursor.getString(0));
            c.setDate(cursor.getString(1));

            byte[] blob1 = cursor.getBlob(cursor.getColumnIndexOrThrow("2"));
            Bitmap bmp1 = BitmapFactory.decodeByteArray(blob1, 0,blob1.length);

            c.setLeftIndexFinger(bmp1);

            byte[] blob2 = cursor.getBlob(cursor.getColumnIndexOrThrow("3"));
            Bitmap bmp2 = BitmapFactory.decodeByteArray(blob1, 0,blob2.length);
            c.setRightIndexFinger(bmp2); 


            // Adding contact to list
            caseList.add(c);
        } while (cursor.moveToNext());
    }

    // return contact list
    return caseList;
}

}

添加方法效果很好,但是当我尝试打电话给 getAllContacts 方法是这样的:

The add method works perfectly, but when I try to call the getAllContacts method, like this:

public ArrayList<Case> getFromDatabase() {

    ArrayList<Case> c = db.getAllContacts();    
    return c; 
}

list = getFromDatabase();

应用崩溃和LogCat中打印出以下内容:

The app crashes and LogCat prints out following:

07-30 12:07:56.570: E/AndroidRuntime(13040): FATAL EXCEPTION: main

在我尝试从数据库中获取记录的方法,就是在比另一个活动添加

这是我的 getAllContacts 方法:

public ArrayList<Case> getAllContacts() {
    ArrayList<Case> caseList = new ArrayList<Case>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CASES;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Case c = new Case();

            c.setCaseNumber(cursor.getString(0));
            c.setDate(cursor.getString(1));

            byte[] blob1 = cursor.getBlob(cursor.getColumnIndexOrThrow("2"));
            Bitmap bmp1 = BitmapFactory.decodeByteArray(blob1, 0,blob1.length);

            c.setLeftIndexFinger(bmp1);

            byte[] blob2 = cursor.getBlob(cursor.getColumnIndexOrThrow("3"));
            Bitmap bmp2 = BitmapFactory.decodeByteArray(blob1, 0,blob2.length);
            c.setRightIndexFinger(bmp2); 


            // Adding contact to list
            caseList.add(c);
        } while (cursor.moveToNext());
    }

    // return contact list
    return caseList;
}

LogCat中信息:

LogCat info:

  E/AndroidRuntime(15058): FATAL EXCEPTION: main
E/AndroidRuntime(15058): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.package.hello/com.package.hello.History}: java.lang.NullPointerException
E/AndroidRuntime(15058):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
E/AndroidRuntime(15058):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
E/AndroidRuntime(15058):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
E/AndroidRuntime(15058):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
E/AndroidRuntime(15058):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(15058):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(15058):    at android.app.ActivityThread.main(ActivityThread.java:4517)
E/AndroidRuntime(15058):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(15058):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(15058):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
E/AndroidRuntime(15058):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
E/AndroidRuntime(15058):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(15058): Caused by: java.lang.NullPointerException
E/AndroidRuntime(15058):    at com.package.hello.History.getFromDatabase(History.java:153)
E/AndroidRuntime(15058):    at com.package.hello.History.onCreate(History.java:49)
E/AndroidRuntime(15058):    at android.app.Activity.performCreate(Activity.java:4533)
E/AndroidRuntime(15058):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
E/AndroidRuntime(15058):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)

在History.java行153是这样的:

The Line 153 in History.java is this:

    ArrayList<Case> c = db.getAllContacts();   

在历史课上,在分贝对象尚未宣布,因为从类该类inherites其中添加方法。

In the history class, the db object hasn't been declared its because this class inherites from the class where the add method is.

编辑3

我的历史课。

public class History extends SuperClass {

ListView lv;
ArrayList<Case> list; 
ArrayList<Case> tempCaseList; 
TextView header;
EditText ed; 
String[] tempList; 
int textLength; 
TextView error;
Boolean[] isPresent;
DatabaseHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setTabBar(R.layout.history); 

    lv = (ListView)findViewById(R.id.listOfCases); 
    list = new ArrayList<Case>(); 

    list = getFromDatabase();

    lv.setAdapter(new CustomAdapter(this, list)); 
    lv.setTextFilterEnabled(true);

    header = (TextView)findViewById(R.id.textView1);
    header.setText("History");
    error = (TextView)findViewById(R.id.error);

    // db = new DatabaseHandler(this);


    tempList = getCaseNumberToTempList(list);
    tempCaseList = createTempList(list); 



    ed = (EditText)findViewById(R.id.editText1);

    ed.addTextChangedListener(new TextWatcher() {



        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {


        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

            textLength = ed.getText().length();
            list.clear(); 
            isPresent = initIsPresentArray(); 

            for (int i = 0; i < tempList.length; i++) {
                for (int j = 0; j < (tempList[i].length()-(textLength-1)); j++) {
                    if (textLength <= tempList[i].length()) {
                        if(isPresent[i] == false){
                            if (ed.getText().toString().equalsIgnoreCase((String) tempList[i].subSequence(j,(j+textLength)))) {
                                list.add(tempCaseList.get(i));
                                isPresent[i] = true;
                        }
                    }
                }
            }
            if(list.size() == 0) {
                error.setText("Not Found"); 
            }
            else {
                error.setText(""); 
            }

            lv.setAdapter(new CustomAdapter(History.this, list)); 
        }
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }
    });


}

public Boolean[] initIsPresentArray() {
    Boolean[] isPresent = new Boolean[tempCaseList.size()];
    for(int i = 0; i < isPresent.length; i++) {
        isPresent[i] = false; 
    }
    return isPresent; 
}

public ArrayList<Case> createTempList(ArrayList<Case> listOfCases) {

    ArrayList<Case> temporaryList = new ArrayList<Case>(); 

    for(Case c : listOfCases) {
        temporaryList.add(c);
    }

    return temporaryList;
}

public String[] getCaseNumberToTempList(ArrayList<Case> caseList) {

    String[] objectCaseNumber = new String[caseList.size()];  

    for(int i = 0; i < caseList.size(); i++) {
        objectCaseNumber[i] = caseList.get(i).getCaseNumber();  
    }

    return objectCaseNumber;

}


public ArrayList<Case> getFromDatabase() {

    ArrayList<Case> c = db.getAllContacts();    
    return c; 
}

 }

FINAL修改

发现我error..I只是忘了初始化。调用它使用该对象的方法之前,分贝对象。但我得到了另一个错误,这是不是这个线程的话题,所以我会发布一个新的线程,如果我再次获得卡住。谢谢。

Found my error..I just forgot the init. the db object before calling the method which uses this object. But I got another error, which is not the topic of this thread so I will post a new thread, if I get stuck again. Thanks.

推荐答案

按照你编辑的code在这里崩溃:

Following your edit, the code is crashing here:

ArrayList<Case> c = db.getAllContacts();   

这里唯一的事情,可能会造成一个 NullPointerException异常分贝本身就是。您需要检查分贝已被正确地在这一点上开始工作。

The only thing here that could be causing a NullPointerException is db itself being null. You need to check that db has been correctly initialised at this point.

我刚才的答复,这仍然是有效的:

My earlier answer, which is still valid:

很难没有看到完整的stracktrace可以肯定的,但是这肯定看起来错了:

It's hard to be sure without seeing the full stracktrace, but this definitely looks wrong:

byte[] blob1 = cursor.getBlob(cursor.getColumnIndexOrThrow("2"));

这是寻找一个名为列2,它不存在。既然你已经知道你要找的BLOB的列索引,你可能是指这样的:

This is looking for a column named "2", which doesn't exist. Since you already know the column index of the blob you're looking for, you probably meant this:

byte[] blob1 = cursor.getBlob(2);

或另外,如果你真的想找到按列名索引:

or alternatively, if you really do want to find the index by column name:

byte[] blob1 = cursor.getBlob(cursor.getColumnIndexOrThrow("rightFinger"));

这篇关于从数据库中获取数据时,SQLite的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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