LuckyLuke
LuckyLuke

Reputation: 49077

Copying database works on emulator but not on device

This works on the emulator but not on my phone. At least it seems so because it does not find the table when I query it on the phone.

This my class that inherits from SQLiteOpenHelper

public class DBHelper extends SQLiteOpenHelper {

private final static String DB_NAME = "klb_db.sqlite";
private final static int DB_VERSION = 1;

private String dbPath;
private Context context;

public DBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

    this.context = context;
    dbPath = "/" + Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/";
}

public void initializeDatabase() {
    try {
        File file = new File(dbPath + DB_NAME);
        if (!file.exists()) {
            InputStream inputStream = context.getAssets().open(
                    "klb_db.sqlite");
            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            inputStream.close();
            outputStream.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

In dbadapter, open method:

    public DBAdapter open() {
    dbHelper.initializeDatabase();
    db = dbHelper.getWritableDatabase();
    return this;
}

In activity that uses it:

    @Override
protected void onStart() {
    super.onStart();

    QuizDAO quizDAO = new QuizDAO(this);
    quizDAO.open();
    Cursor cursor = quizDAO.getQuestion(10);
    Toast.makeText(this, cursor.getString(1), Toast.LENGTH_LONG).show();
}

Upvotes: 0

Views: 237

Answers (1)

try to increase you bytes

byte[] buffer = new byte[1024];

to

byte[] buffer = new byte[2048];

EDITED

@Override
protected void onStart() {
    super.onStart();

    QuizDAO quizDAO = new QuizDAO(this);
    quizDAO.open();
    Cursor cursor = quizDAO.getQuestion(10);
    cursor.moveToFirst()
    Toast.makeText(this, cursor.getString(1), Toast.LENGTH_LONG).show();
}

Upvotes: 2

Related Questions