How to connect external SqliteDatabase to Android application? - java

here is my problem. I am creating my database of text in program called SqliteDbBrowser after that I want to put it into /assets/ folder in android and load it to the application.
All the tutorials assume that you don't have any database and you create it clean from application and then fill it.
I have already put data into my database and don't want to create new one.
Here is some guy's tutorial http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ and it somehow work's but it's not perfect, is it any other way to solve this ? Using ony SQLiteOpenHelper not mixing stuff?

public void getDataBaseData() {
// /PawnStorescopy.db
if (!new File("/data/data/" + this.getPackageName()
+ "/PawnStorescopy.sqlite").exists()) {
try {
FileOutputStream out = new FileOutputStream("data/data/"
+ this.getPackageName() + "DatabaseName.sqlite");
InputStream in = getAssets().open("DatabaseName.db");
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = in.read(buffer)) != -1)
out.write(buffer, 0, readBytes);
in.close();
// out.close();
} catch (IOException e) {
}
}
SQLiteDatabase sqliteDB = SQLiteDatabase.openOrCreateDatabase(
"/data/data/" + this.getPackageName()
+ "/DatabaseName.sqlite", null);
Cursor cursor = sqliteDB.rawQuery("SELECT * FROM TableName", null);
if (cursor.moveToFirst()) {
do {
////Get Data
} while (cursor.moveToNext());
imageFilter(listDatabase);
}
}

I don't see the problem. I used that same example and it worked.
In my project I had to check and, eventually, load the missing tables on the internal DB.
The DB will not be erased, unless you state so.
Therefore adding new tables will not erase any pre-existing ones.
Anyway, you said 'it somehow work's but it's not perfect', what do you mean? It either copies the tables or it doesn't. Right?

The example you provided a link for works well, but the best practice is to build your database within your android application, so you can export the ready database DLL with the data as insert statements, add those insert statements in a file let say under your raw folder and after creating the DB you can read the insert statements and execute them to have your data inserted.

First Put your Created Database in your Asset Folder.
Add Below Java File to your Project
package com.app.ourforms.database;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Vector;
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 DBConnect extends SQLiteOpenHelper {
ArrayList<String> arraylistUrl;
public int GetCursor;
public DBConnect(Context context, String db_name) {
super(context, db_name, null, 2);
if (db != null && db.isOpen())
close();
this.myContext = context;
DB_NAME = db_name;
try {
createDataBase();
openDataBase();
} catch (IOException e) {
// System.out.println("Exception in creation of database : "+
// e.getMessage());
e.printStackTrace();
}
}
public void createDataBase() throws IOException {
// boolean dbExist = checkDataBase();
boolean dbExist = databaseExist();
if (dbExist) {
// System.out.println("Database Exist");
} else {
this.getReadableDatabase();
try {
copyDatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDatabase() throws IOException {
InputStream input = myContext.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream output = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
input.close();
// System.out.println(DB_NAME + "Database Copied !");
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
public boolean isOpen() {
if (db != null)
return db.isOpen();
return false;
}
#Override
public synchronized void close() {
if (db != null)
db.close();
super.close();
}
public boolean databaseExist() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
// System.out.println("My Pathe is:- " + myPath);
// System.out.println("Open");
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
// System.out.println("checkDB value:" + checkDB);
// System.out.println("My Pathe is:- " + myPath);
} catch (Exception e) {
// database does't exist yet.
}
if (checkDB != null) {
// System.out.println("Closed");
checkDB.close();
// System.out.println("My db is:- " + checkDB.isOpen());
}
return checkDB != null ? true : false;
}
public Cursor execCursorQuery(String sql) {
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, null);
GetCursor = cursor.getCount();
Log.i("Inside execCursorQuery try", sql);
} catch (Exception e) {
Log.i("Inside execCursorQuery exception", e.getMessage());
}
return cursor;
}
public void execNonQuery(String sql) {
try {
db.execSQL(sql);
// Log.d("SQL", sql);
} catch (Exception e) {
// Log.e("Err", e.getMessage());
} finally {
// closeDb();
}
}
// ****************** Declare all the global variable
// ****************************//
private Context myContext;
public String DB_PATH = "data/data/com.app.ourforms/databases/"; // path
// of
// your
// datbase
public static String DB_NAME = "OurForms.sqlite";// your database
// name
#SuppressWarnings("unused")
private static String ASSETS_DB_FOLDER = "db";
private SQLiteDatabase db;
public Vector<ArrayList<String>> getQuestion(String Query) {
Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
ArrayList<String> Question = new ArrayList<String>();
ArrayList<String> Option1 = new ArrayList<String>();
ArrayList<String> Option2 = new ArrayList<String>();
ArrayList<String> Option3 = new ArrayList<String>();
ArrayList<String> Option4 = new ArrayList<String>();
ArrayList<String> Option5 = new ArrayList<String>();
ArrayList<String> correct = new ArrayList<String>();
ArrayList<String> correctness = new ArrayList<String>();
ArrayList<String> Description = new ArrayList<String>();
Cursor alldata_ques = execCursorQuery(Query);
// GetCursor = alldata_ques.getCount();
if (alldata_ques != null) {
Log.e("Cursor length", "" + alldata_ques.getCount());
GetCursor = alldata_ques.getCount();
if (alldata_ques.getCount() > 0)
while (alldata_ques.moveToNext()) {
Question.add((alldata_ques.getString(alldata_ques
.getColumnIndex("Question"))));
Option1.add(alldata_ques.getString(alldata_ques
.getColumnIndex("A")));
Option2.add(alldata_ques.getString(alldata_ques
.getColumnIndex("B")));
Option3.add(alldata_ques.getString(alldata_ques
.getColumnIndex("C")));
Option4.add(alldata_ques.getString(alldata_ques
.getColumnIndex("D")));
Option5.add(alldata_ques.getString(alldata_ques
.getColumnIndex("E")));
correct.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Answer")));
correctness.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Correctness")));
Description.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Description")));
}
alldata.add(Question);
alldata.add(Option1);
alldata.add(Option2);
alldata.add(Option3);
alldata.add(Option4);
alldata.add(Option5);
alldata.add(correct);
alldata.add(correctness);
alldata.add(Description);
// Log.d("VECTORSIZE", String.valueOf(alldata.size()));
}
return alldata;
}
public Vector<ArrayList<String>> getQuestions(String Query) {
Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
ArrayList<String> Question = new ArrayList<String>();
ArrayList<String> Option1 = new ArrayList<String>();
ArrayList<String> Option2 = new ArrayList<String>();
ArrayList<String> Option3 = new ArrayList<String>();
ArrayList<String> Option4 = new ArrayList<String>();
ArrayList<String> Option5 = new ArrayList<String>();
ArrayList<String> correct = new ArrayList<String>();
ArrayList<String> Description = new ArrayList<String>();
Cursor alldata_ques = execCursorQuery(Query);
if (alldata_ques != null) {
Log.e("Cursor length", "" + alldata_ques.getCount());
if (alldata_ques.getCount() > 0)
GetCursor = alldata_ques.getCount();
while (alldata_ques.moveToNext()) {
Question.add((alldata_ques.getString(alldata_ques
.getColumnIndex("Question"))));
Option1.add(alldata_ques.getString(alldata_ques
.getColumnIndex("A")));
Option2.add(alldata_ques.getString(alldata_ques
.getColumnIndex("B")));
Option3.add(alldata_ques.getString(alldata_ques
.getColumnIndex("C")));
Option4.add(alldata_ques.getString(alldata_ques
.getColumnIndex("D")));
Option5.add(alldata_ques.getString(alldata_ques
.getColumnIndex("E")));
correct.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Answer")));
Description.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Description")));
}
alldata.add(Question);
alldata.add(Option1);
alldata.add(Option2);
alldata.add(Option3);
alldata.add(Option4);
alldata.add(Option5);
alldata.add(correct);
alldata.add(Description);
// Log.d("VECTORSIZE", String.valueOf(alldata.size()));
}
return alldata;
}
}
In Above Code Change below line as per your project:
public String DB_PATH = "data/data/YOUR_PACKAGE_NAME/databases/"; // path of your datbase
public static String DB_NAME = "OurForms.sqlite";// your database Name
Inside your Activity Write Below Code For First Time Copy your Database to Application.
// For Database Copy
myPrefs = getSharedPreferences("myPrefs", 0);
// sharedPreferences = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext());
Data.FIRST_TIME_LAUNCH = myPrefs.getBoolean("FIRST_TIME_LAUNCH", true);
if (Data.FIRST_TIME_LAUNCH) {
Log.i(TAG, "FIRST TIME*************************");
dbConnect = new DBConnect(getApplicationContext(),
"OurForms.sqlite");
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("FIRST_TIME_LAUNCH", false);
editor.commit();
}
Hope it will help you.

Follow this link:
https://github.com/jgilfelt/android-sqlite-asset-helper
Then,
Add your yourSqliteDb.db to folder in assets/databases. Create the folders if not present.
assets/databases/yourSqliteDb.db
How to create asset folder:
http://code2care.org/2015/create-assets-folder-in-android-studio/
Create SQLiteAssetHelper Class as:
public class MyDatabaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "yourSqliteDb.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context mContext)
{
super(mContext, DATABASE_NAME, null, DATABASE_VERSION );
}
public Cursor getItems()
{
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery("Select * from items", null);
//items is a column name in your table in database
c.moveToFirst();
return c;
}
}
Now in MainActivity or wherever you need to read data from database,
MyDatabaseHelper myDbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = myDbHelper.ReadableDatabase();
String items = getResult(1); //number value from database table
public String getResult(int id)
{
String name = null;
try
{
Cursor c = null;
c = db.rawQuery("select item from items where _id="+id, null);
c.moveToFirst();
name = c.getString(c.getColumnIndex("item"));
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return name;
}

Related

App keeps going to home screen after clicking on a list item

I am trying to create a quiz app where a category can be selected by clicking on a listView item. Each category has code like 0,1,2. For football, it is 0. After clicking on the football item, the app keeps on going to the home screen instead of logging the data I want. Please help me with the error.
Quiz Category Selection Class
String quizCategory = intent.getStringExtra("QuizCategory");
//Deciding which database to Open and choose
switch (quizCategory) {
case "0":
Log.i("Category", "Football");
Football football = new Football(this);
football.createDatabase();
football.openDatabase();
football.getWritableDatabase();
long x=football.getRowCount();
break;
default:
Log.i("Message", "Error");
}
}
Football Class
public class Football extends SQLiteOpenHelper {
private static final String Database_path = "/data/data/com.google.quiz/databases/";
private static final String Database_name = "football.db";
private static Context context;
private static final int version = 1;
public SQLiteDatabase sqlite;
public Football(Context context) {
super(context, Database_name, null, version);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbexist = DBexists();
if (!dbexist) {
this.getReadableDatabase();
copyDBfromResource();
}
}
private void copyDBfromResource() {
InputStream is;
OutputStream os;
String filePath = Database_path + Database_name;
try {
is = context.getAssets().open(Database_name);//reading purpose
os = new FileOutputStream(filePath);//writing purpose
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//writing to file
}
os.flush();//flush the outputstream
is.close();//close the inputstream
os.close();//close the outputstream
} catch (IOException e) {
throw new Error("Problem copying database file:");
}
}
public void openDatabase() throws SQLException {
String myPath = Database_path + Database_name;
sqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean DBexists() {
SQLiteDatabase db = null;
try {
String databasePath = Database_path + Database_name;
db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
} catch (SQLException e) {
Log.e("Sqlite", "Database not found");
}
if (db != null)
db.close();///close the opened file
return db != null ? true : false;
}
public long getRowCount() {
SQLiteDatabase db = this.getReadableDatabase();
long x = DatabaseUtils.queryNumEntries(db, "football");
db.close();
return x;
}
}

How to convert SQLite database in android studio and then share it as csv file

Im making an app in which the users inserts values into a table (SQLite DB) and I want to make a share button which will share the the table as an excel file (.csv).
The following is a rudimentary example. That will write a very basic CSV file based upon a query that concatenates the columns with a , between the columns.
The table has 3 columns named :-
_id
_name
_email
The query used is effectively SELECT _id||','||_name||','||_email FROM test1;, although the SQLiteDatabase query method is used to build the SQL.
The method getCSVRows of the DBHelper class returns a Cursor based upon the above (i.e. a single column, the CSV, that can be accessed via offset 0).
Each time the App is run two rows are added, via the addTest1Row method.
The App has a button that when clicked invokes the crtCSV method that basically :-
gets the column names as a CSV (really this method should be used to drive the getCSVRows method, as there is the potential to have the column names in the wrong place) and writes the line with these first.
retrieves the Cursor with the data as a CSV string and writes a line.
The output file is located in the mycsvfiles directory of the Downloads directory (note only the most basic of checks are done, so this may not work on some devices).
The file name will be unique as it is suffixed with the current timestamp.
This screenshot shows 3 such files (a taken from Android Studio's device Explorer) :-
This shows it opened in Android Studio :-
And lastly in Excel :-
Here's the code:-
First, as Permission is required the relevant section of the Manifest AndroidManifest.xml
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
If the App is to be used for any device that uses an API greater than 22 then permission has to be requested. As such there is a class for this namely ExternalStoragePermissions.java for handling this request :-
class ExternalStoragePermissions {
public int API_VERSION = Build.VERSION.SDK_INT;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public ExternalStoragePermissions() {}
// Note call this method
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
invoked from Main.Activity
The DatabaseHelper (i.e. Subclass of SQLiteOpenHelper, as is often used) is DBHelper.java :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_TEST1 = "test1";
public static final String COL_TEST1_ID = BaseColumns._ID;
public static final String COL_TEST1_NAME = "_name";
public static final String COL_TEST1_EMAIL = "_email";
private static final String crtTest1SQL = "CREATE TABLE IF NOT EXISTS " +
TB_TEST1 +
"(" +
COL_TEST1_ID + " INTEGER PRIMARY KEY," +
COL_TEST1_NAME + " TEXT," +
COL_TEST1_EMAIL + " TEXT" +
")";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(crtTest1SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long addTest1Row(String name, String email) {
ContentValues cv = new ContentValues();
cv.put(COL_TEST1_NAME,name);
cv.put(COL_TEST1_EMAIL,email);
return mDB.insert(TB_TEST1,null,cv);
}
public Cursor getCSVRows(String table) {
Cursor rv;
String[] columns;
switch (table) {
case TB_TEST1:
columns = new String[]{COL_TEST1_ID + "||','||" + COL_TEST1_NAME + "||','||" + COL_TEST1_EMAIL};
break;
default:
return null;
}
return mDB.query(table,columns,null,null,null,null,null);
}
public String getColumnsAsCSV(String table) {
StringBuilder sb = new StringBuilder("");
if (ifTableExists(table)) {
Cursor csr = mDB.rawQuery("PRAGMA table_info(" +
table +
")",null);
boolean after_first_row = false;
int rowsdone = 0;
while (csr.moveToNext()) {
if (after_first_row) {
sb.append(",");
} else {
after_first_row = true;
}
sb.append(csr.getString(csr.getColumnIndex("name")));
}
}
return sb.toString();
}
private boolean ifTableExists(String table) {
String whereclause = "name=?";
String[] whereargs = new String[]{table};
Cursor csr = mDB.query("sqlite_master",null,whereclause,whereargs,null,null,null);
int rowcount = csr.getCount();
csr.close();
return rowcount > 0;
}
}
Last is the Activity MainActivity.java
public class MainActivity extends AppCompatActivity {
Button mConvert;
DBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Need to have permission to External Storage
if(Build.VERSION.SDK_INT >= 23) {
ExternalStoragePermissions.verifyStoragePermissions(this);
}
mConvert = this.findViewById(R.id.convert_table);
mConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
crtCSV(DBHelper.TB_TEST1 + String.valueOf(System.currentTimeMillis()),DBHelper.TB_TEST1);
}
});
mDBHlpr = new DBHelper(this);
mDBHlpr.addTest1Row("Fred","Fred#email.com");
mDBHlpr.addTest1Row("Mary","mary#email.com");
}
private int crtCSV(String filename, String table) {
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return -1;
}
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"mycsvfiles");
String directory = dir.getPath();
if (!dir.exists()) {
dir.mkdirs();
}
File f = new File(directory,filename);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return -2;
}
f.delete();
FileOutputStream fo;
try {
fo = new FileOutputStream(f);
} catch (IOException e) {
e.printStackTrace();
return -3;
}
Cursor csr = mDBHlpr.getCSVRows(table);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));
try {
bw.write(mDBHlpr.getColumnsAsCSV(table));
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
try {
fo.close();
} catch (IOException e1) {
e1.printStackTrace();
f.delete();
return -4;
}
f.delete();
return -5;
}
while (csr.moveToNext()) {
String line = csr.getString(0);
try {
bw.write(line);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
try {
fo.close();
} catch (IOException e1) {
e1.printStackTrace();
f.delete();
return -6;
}
f.delete();
return -7;
}
}
csr.close();
try {
bw.close();
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
return -8;
}
return 0;
}
}
The easiest way, use CSVWriter like this:
implementation 'com.opencsv:opencsv:3.7'
And in MainActivity
try {
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase db = myDb.getWritableDatabase();
Cursor curCSV = db.rawQuery("select * from " + "your_database_table", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String[] arrayStr = {curCSV.getString(0), curCSV.getString(1),
curCSV.getString(2), curCSV.getString(3),
curCSV.getString(4), curCSV.getString(5)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
} catch (IOException e) {
e.printStackTrace();
}
where curCSV.getString() detect the column title, so start from 0 to number of your table column.

Can't load file from Sdcard

i have an app that has database inside the assets folder.
But i want to get the database from my sdcard not from the assets, as i'm new to this, i did these steps :
I downloaded the new DB and put it inside the custom folder.
I changed the DB_PATH from
DB_PATH = "/data/data/com.test.project/databases/";
to
DB_PATH = Environment.getExternalStorageDirectory() + "/my_custom_folder/";
but when i try to access it, the app crashes , and that DB got deleted from my phone, any help ?
Here is the code to load it :
public class book_DB_Helper extends SQLiteOpenHelper {
public final static int DB_VERSION = 1;
private final static String DB_NAME = "my_book";
public static SQLiteDatabase db;
//// --- the old PATH 'from assets folder
//private static String DB_PATH = "/data/data/com.test.project/databases/";
//// --- my new path in the sdcard
private static String DB_PATH = Environment.getExternalStorageDirectory() + "/my_folder/";
private final Context context;
private final String TABLE_NAME = "tbl_recipes";
private final String ID = "id";
private final String RECIPE_NAME = "recipe_name";
private final String IMAGE_PREVIEW = "image_preview";
private final String COOK_TIME = "cook_time";
public my_book_DB_Helper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if (dbExist) {
//do nothing - database already exist
deleteDataBase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
} else {
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void deleteDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
dbFile.delete();
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream 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 void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public void close() {
db.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<ArrayList<Object>> getAllData(String RecipeNameKeyword) {
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
if (RecipeNameKeyword.equals("")) {
try {
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
} else {
try {
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
RECIPE_NAME + " LIKE '%" + RecipeNameKeyword + "%'",
null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
return dataArrays;
}
public ArrayList<Object> getDetail(long id) {
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try {
String SUMMARY = "summary";
String PREP_TIME = "prepare_time";
String SERVES = "serves";
String INGREDIENTS = "ingredients";
String DIRECTIONS = "directions";
cursor = db.query(
TABLE_NAME,
new String[]{RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
ID + "=" + id,
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
rowArray.add(cursor.getString(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
rowArray.add(cursor.getString(5));
rowArray.add(cursor.getString(6));
rowArray.add(cursor.getString(7));
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
return rowArray;
}
}

show data from SQLite to Custom ListView in android studio

I want to show my data from sqlite to Custom ListView (java , Android studio , sqlite ).
But it's force stop.
picture from my Main Activity:
picture from my Database class:
Please Help me!!!!
(my English is not good sorry but can i understand your words)
first you have to create a custom adapter for your listview and populate that adapter with listview and your code should be like this
and to get the data from database create a method in database class name getdata() take it in a form of cursor
public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 3;
public static final String TABLE_NAME = "student";
public static final String DEVICE = "device"; //your coloumn
public static final String ADDRESS = "address";//your coloumn
public static final String Date = "Date"; //your coloumn
public String CREATE_QUERY = "CREATE TABLE "+TABLE_NAME+"("+DEVICE+" TEXT,"+ADDRESS+" TEXT,"+Date+"TEXT);";
public UserDbHelper(Context context)
{
super(context,DATABASENAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_QUERY);
}
public List<Datalist> getdata()
{
List<Datalist> result = new ArrayList<>();
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM Table_name,null";);
while (c.moveToNext()) {
result.add(
new Datalist(
c.getString(c.getColumnIndex("YOUR COLOUMN")),
c.getString(c.getColumnIndex("YOUR COLOUMN")),
date
)
);
}
c.close();
return result;
}
and populate your database with listview
this will be in your button click that button which retrive the data
List<Datalist> itemFromDatabase = getItemFromDatabase();
MyAdapter adapter = new MyAdapter(getApplicationContext(), 0, itemFromDatabase);
listOfDatabaseObject.setAdapter(adapter);
adapter.notifyDataSetChanged();
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDbHelper;
List<String> stringList;
ListView listView;
List<Mivejat> mivejatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDbHelper = new DataBaseHelper(this);
stringList = new ArrayList<>();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
mivejatList = myDbHelper.MiveName();
for (int i = 0 ; 0 < mivejatList.size() ; i++) {
stringList.add(mivejatList.get(i).name);
}
listView = (ListView) findViewById(R.id.listViewMive);
mainListViewClass mainListViewClass = new mainListViewClass(MainActivity.this , stringList);
listView.setAdapter(mainListViewClass);
mainListViewClass.notifyDataSetChanged();
myDbHelper.close();
}
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/mivejat.rezaahmadpour.ir.mivejat/databases/";
private static String DB_NAME = "KhavasMiveha.db";
public static final int DB_VERS = 1;
private SQLiteDatabase myDataBase;
private final Context myContext;
private static String TAG = "KhavasMiveha.db";
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERS);
this.myContext = context;
}
/**
* Creates an empty database on the system and rewrites it with your own
* database.
*/
public boolean createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.d(TAG, "database already exist");
//Running this method causes SQLite class checking for if New DB Version Exists and runs upgrade method
getReadableDatabase();
close();
return true;
} 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");
}
return false;
}
}
/**
* 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 (SQLiteException 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 transferring 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);
}
#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) {
Log.d(TAG, "UPGRADING Database...");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
public List<Mivejat> MiveName() {
String query = "SELECT Name FROM tbl_mive";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
List<Mivejat> result = new ArrayList<>();
Mivejat m;
while (cursor.moveToNext()) {
m = new Mivejat();
m.name = cursor.getString(0);
result.add(m);
}
return result;
}

"A SQLiteConnection was leaked" warning

I have this problem with sqlite, i'm getting this warning:
A SQLiteConnection object for database '//data//data//com.compapps.booster//databases//booster.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
And logcat is showing that continuously, even after closing the app:
Database already exists
So i think the programm perform execution even if the app is closed, here is the code of my class:
package com.compapps.booster.db;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.compapps.booster.model.AppInfo;
import com.compapps.booster.model.UsedAppInfo;
import com.compapps.booster.utill.Const;
public class ExternalDbOpenHelper extends SQLiteOpenHelper {
// Path to the device folder with databases
public static String DB_PATH;
// Database file name
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
public SQLiteDatabase getDb() {
return database;
}
public ExternalDbOpenHelper(Context context, String databaseName,
int databaseVersion) {
super(context, databaseName, null, databaseVersion);
this.context = context;
// Write a full path to the databases of your application
String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}
// This piece of code will create a database if itï؟½s not yet created
public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}
// Performing a database existence check
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
}
// Android doesnt like resource leaks, everything should
// be closed
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}
// Method for copying the database
private void copyDataBase() throws IOException {
// Open a stream for reading from our ready-made database
// The stream source is located in the assets
InputStream externalDbStream = context.getAssets().open(DB_NAME);
// Path to the created empty database on your Android device
String outFileName = DB_PATH + DB_NAME;
// Now create a stream for writing the database byte by byte
OutputStream localDbStream = new FileOutputStream(outFileName);
// Copying the database
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
// Dont forget to close the streams
localDbStream.close();
externalDbStream.close();
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
}
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
return database;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertAutoKillApps(final ArrayList<AppInfo> listAutoKillApps) {
for (int i = 0; i < listAutoKillApps.size(); i++) {
if (listAutoKillApps.get(i).isChecked()) {
AppInfo info = listAutoKillApps.get(i);
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME,
info.getPkgName());
values.put(Const.TblAutoKillColumn.PROCESS_ID,
info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null,
values);
}
}
}
public int insertAutoKillApp(AppInfo info) {
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME, info.getPkgName());
// values.put(Const.TblAutoKillColumn.PROCESS_ID, info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null, values);
return id;
}
public int insertAllAutoKillApp(ArrayList<AppInfo> list) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
AppInfo info = list.get(i);
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME, info.getPkgName());
// values.put(Const.TblAutoKillColumn.PROCESS_ID,
// info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null, values);
if (id != -1) {
count += 1;
}
}
System.out.println("Total app kill inserted " + count);
return count;
}
public boolean deleteAutoKillApp(AppInfo info) {
int row = database.delete(Const.TABLE_AUTO_KILL,
Const.TblAutoKillColumn.PACKAGE_NAME + " = ?",
new String[] { info.getPkgName() });
if (row != 0) {
return true;
}
return false;
}
public int deleteAllAutoKillApp(ArrayList<AppInfo> list) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
AppInfo info = list.get(i);
int row = database.delete(Const.TABLE_AUTO_KILL,
Const.TblAutoKillColumn.PACKAGE_NAME + " = ?",
new String[] { info.getPkgName() });
if (row != 0) {
count += 1;
}
}
System.out.println("Total app kill deleted " + count);
return count;
}
public ArrayList<AppInfo> getAutoKillApps() {
ArrayList<AppInfo> appList = new ArrayList<AppInfo>();
String selectQuery = "SELECT * FROM " + Const.TABLE_AUTO_KILL;
Cursor cursor = database.rawQuery(selectQuery, null);
try {
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
AppInfo info = new AppInfo();
info.setAppName(cursor.getString(0));
info.setPkgName(cursor.getString(1));
// info.setProcessId(cursor.getInt(2));
appList.add(info);
} while (cursor.moveToNext());
}
}
return appList;
} catch (Exception e) {
Log.d("Error in getting app auto kill from DB", e.getMessage());
return appList;
}
finally{
cursor.close();
}
}
public int insertUsedAppInfo(UsedAppInfo uAppInfo, boolean isUpdate) {
int id = 0;
if (isUpdate) {
ContentValues values = new ContentValues();
values.put(Const.TblAppUsedColumn.OPEN_COUNTER,
uAppInfo.getCounter());
values.put(Const.TblAppUsedColumn.OPEN_TIME, uAppInfo.getTime());
String[] args = new String[] { uAppInfo.getPackage_name() };
id = (int) database.update(Const.TABLE_APP_USED_DETAIL, values,
Const.TblAppUsedColumn.PACKAGE_NAME + "=?", args);
} else {
ContentValues values = new ContentValues();
values.put(Const.TblAppUsedColumn.PACKAGE_NAME,
uAppInfo.getPackage_name());
values.put(Const.TblAppUsedColumn.OPEN_COUNTER,
uAppInfo.getCounter());
values.put(Const.TblAppUsedColumn.OPEN_TIME, uAppInfo.getTime());
id = (int) database.insert(Const.TABLE_APP_USED_DETAIL, null,
values);
}
return id;
}
public UsedAppInfo gettUsedAppInfo(String packageName) {
UsedAppInfo uAppInfo = null;
String selectQuery = "SELECT * FROM " + Const.TABLE_APP_USED_DETAIL
+ " WHERE " + Const.TblAppUsedColumn.PACKAGE_NAME + " = "
+ "\"" + packageName + "\"";
System.out.println("Query coding: " + selectQuery);
try {
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
uAppInfo = new UsedAppInfo();
uAppInfo.setPackage_name(cursor.getString(0));
uAppInfo.setCounter(cursor.getInt(1));
uAppInfo.setTime(cursor.getString(2));
}
cursor.close();
}
return uAppInfo;
} catch (Exception e) {
Log.d("Error in getting app info from db", e.getMessage());
return null;
}
}
#Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
}
Can I have help please, thanks!

Categories

Resources