2017年4月28日 星期五

[Android] Read the Database from your APP

1. If you don't have the Database for your APP yet, you could refer to "[Android][SQLite] Generate the Database for your APP" to generate a database.
2. Here is an example and several steps to shows you how to read the Database from your APP.
Step1. Start a new Android Studio project.



Step2. Create a "assets" folder under "\app\src\main" path and then move or copy the Database "TBS_DL.db"  to the "assets" folder.




Step3. Create a new Java Class file.




Step4. Use "extends SQLiteOpenHelper" in the file "MyDBHelper.java".



Step5. Here is the entire "MyDBHelper.java" code for your reference.

package com.programmer.samuel_liang.readdb;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

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

public class MyDBHelper extends SQLiteOpenHelper {

    private static String PACKAGE_NAME = "com.programmer.samuel_liang.readdb";
    private static String DB_PATH = "/data/data/" + PACKAGE_NAME + "/databases/";
    public static String DB_NAME = "TBS_DL.db";

    private final Context mCtx;

    public MyDBHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.mCtx = context;
    }

    public boolean createDatabase() {
        boolean dbExist = checkDatabase();
        this.getReadableDatabase();
        if (dbExist == false) {
            if (copyDatabase() == false) {
                return false;
            }
        }
        return true;
    }

    public boolean checkDatabase() {
        SQLiteDatabase checkDB = null;
        String dbpath = DB_PATH + DB_NAME;
        try {
            checkDB = SQLiteDatabase.openDatabase(dbpath,
                    null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            return false;
        }
        if (checkDB != null) {
            checkDB.close();
            return true;
        }
        return false;
    }

    //Copy "TBS_DL.db" from assets folder to "DB_PATH + DB_NAME"
    private boolean copyDatabase() {
        try {
            //Read "TBS_DL.db" from assets folder
            InputStream input = mCtx.getAssets().open(DB_NAME);
            this.getReadableDatabase();
            String outFileName = DB_PATH + DB_NAME;
            OutputStream output =
                    new FileOutputStream(outFileName);
            byte [] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override    public void onCreate(SQLiteDatabase db) {

    }

    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


Step6. For example, we need to read the data in red from the database...
 


Step7. Here is the entire "MainActivity.java" code for your reference.
package com.programmer.samuel_liang.readdb;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //Database    private SQLiteDatabase TBS_DL_db;
    Cursor TBS_cursor;
    int int_MCS_index = 0;
    int int_TBS = 0;
    String str_RB;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //DATABASE
        MyDBHelper dbHelper = new MyDBHelper(this);

        //Check if we can open TBS_DL.db
        if (dbHelper.createDatabase() == false) {
            Toast.makeText(this, "Can not open Database for TBS_DL.db",Toast.LENGTH_SHORT).show();
        }
        else{
            //Toast.makeText(this, "Open Database successfully",Toast.LENGTH_SHORT).show();
            TBS_DL_db = openOrCreateDatabase("TBS_DL.db",MODE_PRIVATE,null);
        }

        //Use SQLite command to read all data from TBS_DL database.
        TBS_cursor = TBS_DL_db.rawQuery("select * from TBS_DL",null);

        //Read the data from the database.
        int_MCS_index = 2;
        str_RB = "15RB";

        TBS_cursor.moveToPosition(int_MCS_index);
        int_TBS = TBS_cursor.getInt(TBS_cursor.getColumnIndex(str_RB));
        Toast.makeText(this, "The data is " + Integer.toString(int_TBS),Toast.LENGTH_SHORT).show();

    }
}

Step8Run the APP. If everything is OK, you will see...


Step9. Done!!