0

SQLite 数据库截图

助手类:

package com.deangrobler.myApp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;

public class DataBaseHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.deangrobler.chumperoo/databases/"; 
private static String DB_NAME = "ChumperooDB.db"; 
private SQLiteDatabase myDataBase; 

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}   

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
           //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database: " + e.getStackTrace());

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}

@Override
public synchronized void close() {

        if(myDataBase != null)
            myDataBase.close();

        super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

//Queries the database
public Cursor queryDataBase(String table, String[] columns, String selection){

    return myDataBase.query(table, columns, selection, null, null, null, null);

}

}

在我的 Main.java 中使用如下:

DataBaseHelper myDbHelper = new DataBaseHelper(this);

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database"); 
    }

    try {
        myDbHelper.openDataBase();
    }catch(SQLException sqle){
        throw sqle;
    }

    //Get cursor and print out data
    Cursor returnedCur = myDbHelper.queryDataBase("Expenses", new String[]{"Name","Amount"}, null);
    if (returnedCur.moveToFirst()){
        do{
            String data = returnedCur.getString(returnedCur.getColumnIndex("data"));
            System.out.println("Returned Data: "+data);

        }while(returnedCur.moveToNext());
    }
    returnedCur.close();

最后我的整个日志:

> 06-05 13:28:35.885: E/CursorWindow(733): Bad request for field slot 0,-1. numRows = 1, numColumns = 2
06-05 13:28:35.885: D/AndroidRuntime(733): Shutting down VM
06-05 13:28:35.885: W/dalvikvm(733): threadid=1: thread exiting with uncaught exception (group=0x40015560)
06-05 13:28:35.904: E/AndroidRuntime(733): FATAL EXCEPTION: main
06-05 13:28:35.904: E/AndroidRuntime(733): **java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deangrobler.chumperoo/com.deangrobler.chumperoo.Main}: java.lang.IllegalStateException: get field slot from row 0 col -1 failed**
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.os.Looper.loop(Looper.java:123)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread.main(ActivityThread.java:3647)
06-05 13:28:35.904: E/AndroidRuntime(733):  at java.lang.reflect.Method.invokeNative(Native Method)
06-05 13:28:35.904: E/AndroidRuntime(733):  at java.lang.reflect.Method.invoke(Method.java:507)
06-05 13:28:35.904: E/AndroidRuntime(733):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-05 13:28:35.904: E/AndroidRuntime(733):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-05 13:28:35.904: E/AndroidRuntime(733):  at dalvik.system.NativeStart.main(Native Method)
06-05 13:28:35.904: E/AndroidRuntime(733): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.database.CursorWindow.getString_native(Native Method)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.database.CursorWindow.getString(CursorWindow.java:329)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
06-05 13:28:35.904: E/AndroidRuntime(733):  at com.deangrobler.chumperoo.Main.onCreate(Main.java:55)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-05 13:28:35.904: E/AndroidRuntime(733):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
06-05 13:28:35.904: E/AndroidRuntime(733):  ... 11 more
06-05 13:28:53.264: I/Process(733): Sending signal. PID: 733 SIG: 9

不知道为什么会这样,我已经用谷歌搜索了半天了,没有什么能帮助我解决这个问题:-(

4

1 回答 1

3
new String[]{"Name","Amount"}

您正在询问“数据”字段,但我在您的数据库中找不到任何字段名称“数据”。你可以试试

String name = returnedCur.getString(returnedCur.getColumnIndex("Name"));
于 2012-06-05T11:36:36.610 回答