简体   繁体   中英

Android SQLite connect to a database in assets

I'm trying to understand how the connectivity works. I'm required to have a database in the assets folder(which I already built).
I got an entire class adapter, was told to implement it in my code and start using it, but I'm not sure how to 'import' it.
My main class is 'MainActivity', I tried DBAdapter adapter = new DBAdapter(); but that didn't work.

Here's the adapter class:

    package com.example.movieass;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

    public class DBAdapter {
    public static final String KEY_ID = "m_id";
    public static final String KEY_TITLE = "m_title";
    public static final String KEY_DESCRIPTION = "m_description";
    public static final String KEY_RATING = "m_rating";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "database";
    private static final String DATABASE_TABLE = "films";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE =
        "CREATE TABLE trailer (m_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "m_title TEXT NOT NULL, m_description TEXT NOT NULL, m_rating REAL NOT NULL);";

    private final Context context;    

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            try {
                db.execSQL("DROP TABLE IF EXISTS trailer");
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS trailer");
            onCreate(db);
        }
    } //end DatabaseHelper class  

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }

    //---insert a contact into the database---
    public long insertTrailer(String title, String description, String filename, double rating) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_DESCRIPTION, description);
        initialValues.put(KEY_RATING, rating);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular contact---
    public boolean deleteTrailer(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
    }

    //---retrieves all the contacts---
    public Cursor getAllTrailers() 
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_TITLE,
                KEY_DESCRIPTION, KEY_RATING}, null, null, null, null, null);
    }

    //---retrieves a particular contact---
    public Cursor getTrailer(long rowId) throws SQLException 
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ID,
                KEY_TITLE, KEY_DESCRIPTION, KEY_RATING}, KEY_ID + "=" + rowId, null,
                null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
            do{
                Log.d("DBAdapter", "ID: " + mCursor.getString(mCursor.getColumnIndex("ID")));
            }while (mCursor.moveToNext());
        }
        return mCursor;
    }

    //---updates a contact---
    public boolean updateTrailer(long rowId, String title, String description, String filename, double rating) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_DESCRIPTION, description);
        args.put(KEY_RATING, rating);
        return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
    }

    public boolean updateRating(long rowId, double rating) 
    {

        ContentValues args = new ContentValues();
        args.put(KEY_RATING, rating);
        return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;

    }
}

This is my working code to copy database.

private static String DB_PATH = "/data/data/com.demo.databaseDemo/databases/";
 private static String DB_NAME = "myDatabase.db";   
 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();

        }//end of copyDataBase() method

Also You can refer this for more details http://mobisys.in/blog/2012/01/tutorial-using-database-in-android-applications/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM