尝试从sqlite文件读取时出错(Logcat:SQLiteException)

时间:2015-07-06 12:55:04

标签: android sqlite

我已经创建了一个sqlite文件,并放在了projects目录中。它仍然是空的,但我运行我的程序,看它是否工作 - 它没有(我写了一个特定的日志作为指示)。 这是SQLiteOpenHelper子类的代码。非常感谢你。

import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

class DatabaseLoader extends SQLiteOpenHelper
{
    private static DatabaseLoader instance;
    private Map<String,Password> passwords ;
    private static final String ERROR_OPEN_FILE_TAG = "Error Opening File";
    private static final String DATABASE_NAME = "passwords.sql";
    private static final int DATABASE_VERSION = 1;

    public static synchronized DatabaseLoader getInstance( Context context ) 
    {
        if (instance == null) 
        {
          instance = new DatabaseLoader( context.getApplicationContext() );
        }
        return instance;
    }

    private DatabaseLoader( Context context ) {
        super( context, DATABASE_NAME, null, DATABASE_VERSION );
    }

    public Map<String,Password> loadDatabase()
    {
        try
        {
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor result =  db.rawQuery( "select * from passwords", null );
            result.moveToFirst();

            while( !result.isAfterLast() )
            {
                String password = result.getString( 1 );
                int date = result.getInt( 2 );
                passwords.put( password , new Password( password, date) );
                result.moveToNext();
            }
        }
        catch( SQLiteException errorOpeningDB )
        {
            Log.d( ERROR_OPEN_FILE_TAG, "SQLiteException - error opening db for writing" );
        }

        return passwords;
    }



    @Override
    public void onCreate( SQLiteDatabase db )
    {
        // TODO Auto-generated method stub

    }

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

    }
}

2 个答案:

答案 0 :(得分:0)

将您的SQLite Database文件放入Assets并使用此代码

public class DataBaseHelper extends SQLiteOpenHelper {

// The Android's default system path of your application database.
private static String DB_PATH = "";
private static final String DB_NAME = "DBNAME.db";
private static final int DB_VERSION = 1;

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, DB_VERSION);
    this.myContext = context;
    DB_PATH = context.getApplicationInfo().dataDir + File.separator
            + "databases" + File.separator;
}

/**
 * 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
        // Toast.makeText(myContext, "already exist",
        // Toast.LENGTH_LONG).show();
    } 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);
        // Toast.makeText(myContext, "already exist",
        // Toast.LENGTH_LONG).show();
    } catch (SQLiteException e) {
        // database does't exist yet.
        // Toast.makeText(myContext, "not already exist",
        // Toast.LENGTH_LONG).show();
    }
    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 Input file to the output file
    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 arg0) {
    // TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub
}

// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.
}

希望这能解决你的问题!!!!!

答案 1 :(得分:0)

在您的应用中嵌入数据库通常是个坏主意。如果您决定这样做,则需要在首次启动时将数据库从应用程序资产文件夹复制到数据文件夹,然后才能打开它进行编写。

在应用程序中从头开始创建数据库可能更容易,特别是如果它是空的。