Reputation: 1714
I need help to retrieve data from the database in the asset folder by using getter and setter. I dont have any idea on how to retrieve the data since im new to android. What will be the code to be add to retrieve data in the database.
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.user.displayname/databases/";
private static String DB_NAME = "displayname";
private SQLiteDatabase myDataBase;
private Context myContext = null;
public DatabaseHelper(Context context) {
super(context, DB_NAME, (SQLiteDatabase.CursorFactory) null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = this.checkDataBase();
if(!dbExist) {
this.getReadableDatabase();
try {
this.copyDataBase();
} catch (IOException e) {
throw new Error("Error");
}
}
}
public void copyDataBase() throws IOException {
InputStream myInput = this.myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
FileOutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String e = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(e, (SQLiteDatabase.CursorFactory)null, 0);
} catch (SQLiteException e) {
;
}
if(checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
this.myDataBase = SQLiteDatabase.openDatabase(myPath, (SQLiteDatabase.CursorFactory)null, 0);
}
public synchronized void close() {
if(this.myDataBase != null) {
this.myDataBase.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDatabase() {
}
}
Upvotes: 0
Views: 122
Reputation: 1882
Please check below code which is work for me:
private static String DB_NAME ="Your_Db_Name";// Database name
DB_NAME here is the name of your database. And you have a copy of the database in the assets folder, so for example if your database name is todoExample, then the value of DB_NAME will be todoExample,
private static String DB_NAME ="todoExample";
DataHelper.java
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.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper";
private static String DB_PATH = "";
private static String DB_NAME ="todoExample";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
public void createDataBase() throws IOException
{
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
@Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
}
DataAdapter.java
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DataAdapter
{
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public DataAdapter(Context context)
{
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public DataAdapter createDatabase() throws SQLException
{
try
{
mDbHelper.createDataBase();
}
catch (IOException mIOException)
{
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public DataAdapter open() throws SQLException
{
try
{
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
}
catch (SQLException mSQLException)
{
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close()
{
mDbHelper.close();
}
public Cursor getTodoData()
{
try
{
String sql ="SELECT * FROM list";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}
Todo.java
package com.example.todo;
public class Todo {
private String name;
private String note;
public Todo() {
}
public Todo(String name, String note) {
this.name = name;
this.note = note;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
Now you can use it like:
List<Todo> todoItem = new ArrayList<Todo>();
DataAdapter mDbHelper = new DataAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor cursor = mDbHelper.getTodoData();
if (cursor.moveToFirst()) {
do {
Todo todo = new Todo();
todo.setName(cursor.getString(1));
todo.setNote(cursor.getString(2));
todoItem.add(todo);
} while (cursor.moveToNext());
}
mDbHelper.close();
Upvotes: 1
Reputation: 52800
You can do this way:
DBAdapter.java:
Here you have to change two lines:
public static final String DATABASE_NAME = "my_db_title";
public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/";
DBAdapter Class:
public class DBAdapter extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private final Context myContext;
public static final String DATABASE_NAME = "my_db_title";
public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/";
public static final int DATABASE_VERSION = 1;
// public static final int DATABASE_VERSION_old = 1;
// Constructor
public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
// Create a empty database on the system
public void createDatabase(Context ctx) throws IOException {
boolean dbExist1 = checkDataBase();
if (!dbExist1) {
this.getReadableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// Check database already exist or not
private boolean checkDataBase() {
boolean checkDB = false;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
File dbfile = new File(myPath);
checkDB = dbfile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
// Copies your database from your local assets-folder to the just created
// empty database in the system folder
private void copyDataBase() throws IOException {
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
// delete database
public void db_delete() {
File file = new File(DATABASE_PATH + DATABASE_NAME);
if (file.exists()) {
file.delete();
System.out.println("delete database file.");
}
}
// Open database
public void o() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void c() throws SQLException {
if (myDataBase != null)
myDataBase.close();
super.close();
}
public void onCreate(SQLiteDatabase db) {
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
Log.v("Database Upgrade", "Database version higher than old.");
db_delete();
}
}
// Other stuff
}
In Activity or Fragment:
private DBAdapter mDbAdapter;
On onCreate():
mDbAdapter = new DBAdapter(mContext);
try {
mDbAdapter.createDatabase(mContext);
} catch (IOException e) {
e.printStackTrace();
}
Done
Upvotes: 0
Reputation: 763
You can not write to files in Assets direcotry. The database is frequently save here:
string dbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "Database.db3");
And loading can be done for example (C# xamarin)
public static List<Cars> GetCars(int id, ref string logText)
{
List<Cars> ret = null;
string dbPath = EVODatabase.GetDBPath();
try
{
using (SQLiteConnection conn = new SQLiteConnection(dbPath))
{
object[] param = new object[0];
SQLiteCommand cmd = conn.CreateCommand("select * from Cars where id = " + id, param);
ret = cmd.ExecuteQuery<Cars>();
}
}
catch (Exception ex)
{
logText += "\n" + ex.Message + "\n" + ex.StackTrace + "\n" + ex.InnerException;
}
return ret;
}
Upvotes: 0