RuntimeException从SQLite数据库中检索数据

时间:2012-11-14 14:52:50

标签: android-sqlite

我已将数据库导入SQLite(testing.sqllite),这是在Firefox插件的SQLliteManager中创建的。我把它放在数据/数据// databases /.

当我尝试从数据库中检索数据时,我遇到了运行时异常。这是我的代码......

DataBaseHelper.java

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.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{

       public static final String KEY_ROWID = "keyno";
       public static final String DESTINATION = "Destination";
       public static final String CITY = "City";
       public static final String COUNTRY = "Country";
       public static final String IMG1 = "Img1";

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.world.destinations/databases/";

    private static String DB_NAME = "testing";

    private static String DATABASE_TABLE = "Master";

    private DataBaseHelper ourHelper;

    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");

            }
        }

    }

    /**
     * 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;
    }

    public DataBaseHelper open() throws SQLiteException {

        ourHelper = new DataBaseHelper(myContext);
        myDataBase = ourHelper.getWritableDatabase();
        return this;
    }

    /**
     * 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_READONLY);

    }

    @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) {

    }
    public String getData() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{KEY_ROWID, DESTINATION, CITY, COUNTRY, PERIOD, TYPE, CURRENCY, ELEVATION, BRIEF, HIGHLIGHTS, IMG_MAIN};
        Cursor c = myDataBase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(DESTINATION);
        int iCity = c.getColumnIndex(CITY);
        int iCountry = c.getColumnIndex(COUNTRY);
        int iImgmain = c.getColumnIndex(IMG1);

        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iCity) + " " + c.getString(iCountry) + " " + c.getString(iImgmain) + "\n";

        }

        return result;
    } 

}

这是我的 ShowData.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ShowData extends Activity{


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.showdata);
        TextView tv = (TextView)findViewById(R.id.textView1);
        DataBaseHelper info = new DataBaseHelper(this);
        info.open();
        String data = info.getData();
        info.close();
        tv.setText(data);

    }

}

这是例外......

11-14 20:19:29.099: E/AndroidRuntime(933): FATAL EXCEPTION: main
11-14 20:19:29.099: E/AndroidRuntime(933): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.world.destinations/com.world.destinations.ShowData}: android.database.sqlite.SQLiteException: no such table: Master (code 1): , while compiling: SELECT keyno, Destination, City, Country, Img_Main FROM Master
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.os.Looper.loop(Looper.java:137)
11-14 20:19:29.099: E/AndroidRuntime(933):  at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 20:19:29.099: E/AndroidRuntime(933):  at java.lang.reflect.Method.invokeNative(Native Method)
11-14 20:19:29.099: E/AndroidRuntime(933):  at java.lang.reflect.Method.invoke(Method.java:511)
11-14 20:19:29.099: E/AndroidRuntime(933):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

有人可以在我出错的地方帮助我。非常感激。感谢。

1 个答案:

答案 0 :(得分:0)

您正在尝试查询空数据库。

从堆栈跟踪:

  

SQLiteException:没有这样的表:Master(代码1):,同时编译:SELECT keyno,Destination,City,Country,Img_Main FROM Master

我的猜测是你把文件放在sd卡上的错误目录中,而SQLite在其他地方创建了一个空数据库。