lundi 7 décembre 2015

using own sqlite database with android

I'm trying to use a pre-created database that I'e placed in my assets folder. It seems to be opening the database alright but I can't retrieve any values. Here is my DatabaseHelper class:

package com.example.me.app3movies1_1;


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

import android.content.Context;
import android.database.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper{

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

    private static String DB_NAME = "database.sqlite";

    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 DBHelper(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(Exception 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_READONLY);

    }
///////
        public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from videos where id=" + id + "", null);
        return res;
    }
// ///////

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

    }

    // 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.

}


/***************************************************************************************/

//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Hashtable;
//
//import android.content.ContentValues;
//import android.content.Context;
//import android.database.Cursor;
//import android.database.DatabaseUtils;
//import android.database.sqlite.SQLiteOpenHelper;
//import android.database.sqlite.SQLiteDatabase;
//
//public class DBHelper extends SQLiteOpenHelper {
//
//    public static final String DATABASE_NAME = "database.sqlite";
//    public static final String VIDEOS_TABLE_NAME = "videos";
//    public static final String VIDEOS_COLUMN_ID = "id";
//    public static final String VIDEOS_COLUMN_TITLE = "vidTitle";
//    public static final String VIDEOS_COLUMN_DESC = "vidDesc";
//    public static final String VIDEOS_COLUMN_VIDEO = "vidID";
//    public static final String VIDEOS_COLUMN_THUMB = "thumbID";
//    public static final String VIDEOS_COLUMN_RATING = "rating";
//    private HashMap hp;
//
//    public DBHelper(Context context) {
//        super(context, DATABASE_NAME, null, 1);
//    }
//
//    @Override
//    public void onCreate(SQLiteDatabase db) {
//        // TODO Auto-generated method stub
//        db.execSQL(
//                "drop table VIDEOS;" +
//                        "create table VIDEOS " +
//                        "(id integer primary key, " +
//                        "vidTitle text," +
//                        "vidDesc text," +
//                        "vidID integer, " +
//                        "thumbID integer," +
//                        "rating real);"
//        );
//    }
//
//    @Override
//    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        // TODO Auto-generated method stub
//        db.execSQL("DROP TABLE IF EXISTS videos");
//        onCreate(db);
//    }
//
//    public boolean insertVideo(String vidTitle, String vidDesc, Integer vidID, Integer thumbID) {
//        SQLiteDatabase db = this.getWritableDatabase();
//        ContentValues contentValues = new ContentValues();
//        contentValues.put("vidTitle", vidTitle);
//        contentValues.put("vidDesc", vidDesc);
//        contentValues.put("vidID", vidID);
//        contentValues.put("thumbID", thumbID);
//        contentValues.put("rating", 0);
//
//        db.insert("videos", null, contentValues);
//        return true;
//    }
//
//    public Cursor getData(int id) {
//        SQLiteDatabase db = this.getReadableDatabase();
//        Cursor res = db.rawQuery("select * from videos where id=" + id + "", null);
//        return res;
//    }
//
//    public int numberOfRows() {
//        SQLiteDatabase db = this.getReadableDatabase();
//        int numRows = (int) DatabaseUtils.queryNumEntries(db, VIDEOS_TABLE_NAME);
//        return numRows;
//    }
//
//    public boolean updateVideo(Integer id, String vidTitle, String vidDesc, Integer vidID, Integer thumbID, Float rating) {
//        SQLiteDatabase db = this.getWritableDatabase();
//        ContentValues contentValues = new ContentValues();
//        contentValues.put("vidTitle", vidTitle);
//        contentValues.put("vidDesc", vidDesc);
//        contentValues.put("vidID", vidID);
//        contentValues.put("thumbID", thumbID);
//        contentValues.put("rating", rating);
//        db.update("videos", contentValues, "id = ? ", new String[]{Integer.toString(id)});
//        return true;
//    }
//
//    public Integer deleteVideo(Integer id) {
//        SQLiteDatabase db = this.getWritableDatabase();
//        return db.delete("videos",
//                "id = ? ",
//                new String[]{Integer.toString(id)});
//    }
//
//    public void insertRating(int id, Float rating) {
//        SQLiteDatabase db = this.getWritableDatabase();
////        ContentValues contentValues = new ContentValues();
////        contentValues.put("rating", rating);
////        db.update("videos", contentValues, "id = ? ", new String[]{Integer.toString(id)});
//        //String strSQL = "ALTER TABLE videos ADD COLUMN rating real;";
//id = id + 1;
//        String strSQL = "UPDATE videos SET rating = " + rating + " WHERE id = "+ id;
//
//        db.execSQL(strSQL);
//    }
//    public void deleteRating(int id) {
//        SQLiteDatabase db = this.getWritableDatabase();
////        ContentValues contentValues = new ContentValues();
////        contentValues.put("rating", rating);
////        db.update("videos", contentValues, "id = ? ", new String[]{Integer.toString(id)});
//        //String strSQL = "ALTER TABLE videos ADD COLUMN rating real;";
//        id = id + 1;
//        String strSQL = "DELETE FROM videos WHERE id = " + id;
//
//        db.execSQL(strSQL);
//    }
//    public ArrayList<String> getAllVideos() {
//        ArrayList<String> array_list = new ArrayList<String>();
//
//        //hp = new HashMap();
//        SQLiteDatabase db = this.getReadableDatabase();
//        Cursor res = db.rawQuery("select * from videos", null);
//        res.moveToFirst();
//
//        while (res.isAfterLast() == false) {
//            array_list.add(res.getString(res.getColumnIndex(VIDEOS_COLUMN_TITLE)));
//            res.moveToNext();
//        }
//        return array_list;
//    }
//}

And here is where I'm using a cursor to retrieve it:

 DBHelper db = new DBHelper(this);
            try {
                db.createDataBase();
            } catch (IOException ioe) {
                throw new Error("Unable to create database");
            }
            try {
                db.openDataBase();
            }catch(SQLException sqle) {
                throw sqle;
            }

        int i = 1;
        Cursor rs = db.getData(i);//gets data from this particular ID
        if(rs.moveToFirst() && rs.getCount() >= 1) {
            do {


                String test = rs.getString(rs.getColumnIndex("vidTitle"));//gets title info

                Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show();//TEST

                if (!rs.isClosed())//closes cursor
                {
                    rs.close();
                }
            } while (rs.moveToNext());
        }
            db.close();

The name of the field I'm trying to access is "vidTitle" from the "videos" table. I'm using the instructions from this post: http://ift.tt/1QbECRd

It isn't coming up with any errors but I'm also not getting the vidTitle value from my cursor.

Aucun commentaire:

Enregistrer un commentaire