I am trying to search an item in sqlite by using String, & trying to return description contained in that row. items are stored in the table named Articles with column name A_name, Description column name is AS_name
This is my code, the cursor is not null, but the while loop is not getting executed once
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.moveToFirst())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("A_name")));
//temp2 =(cursor.getString(cursor.getColumnIndex("AS_name")));
Log.e("running", "id email" +temp+ " name"+temp2);
}
}
return temp;
}
I want to return the corresponding element of AS_name, also I am confused what should I wrote in while loop ?
Can anyone please identify my mistake, Thanks in advance...
UPDATE DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper
{
//CustomAdapter adapter;
static String name = "law6.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ 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();
/*
InputStream is = v.getAssets().open("quiz.sqlite");
// System.out.println(is.available());
System.out.println(new File(path + "/" + name).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(path + "/" + name);
int num = 0;
while ((num = is.read()) > 0) {
fos.write((byte) num);
}
fos.close();
is.close();*/
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setId(c1.getString(0));
q1.setA_id(c1.getString(1));
q1.setA_name(c1.getString(2));
q1.setAS_name(c1.getString(3));
q1.setDesc_art(c1.getString(4));
// q1.setAct(c1.getString(5));
q1.setExtra(c1.getString(6));
q1.setPart(c1.getString(7));
q1.setItalic(c1.getString(8));
Log.v("AS_name",q1.AS_name);
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
Log.v("", ""+cursor.getCount());
while(cursor.moveToNext())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("AS_name")));
// temp2 =(cursor.getString(cursor.getColumnIndex(name)));
Log.e("running", "desc" +temp);
}
}
return temp;
}
}
UPDATE after implementing rajaji answer, I got this error :
try this it will help you
create the raw query for getting the data
public String searchData(String text)
{
String strvalue=null;
SQliteDatabase db=this.getwritabledatabase();
Cursor cur=null;
String strquery="select * from youurtablename where A_name="+text;
cur=db.rawQuery(strquery,null);
if(cur!=null&&cur.moveToFirst())
{
do
{
strvalue=cur.getString(0);
}
while(cur.moveToNext());
}
}
let me inform once you complete
Is your Uri correct??
create Uri depends on your package name and table name, like the code below :
private static final String AUTHORITY = "com.sample.test_db_provider";
private static final String BASE_PATH = "Tables";
private static final Uri Sample_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH
+ "/SampleTable");
Then in your get Method, query the db like the below code with Uri
cur = m_Resolver.query(Sample_URI, new String[] {"A_name","AS_name"},
"SampleTable.A_name = " + text, null, null);
if(cur != null && cur.moveToFirst())
{
do
{
...
}
while(cur.moveToNext());
}
cur.close();
I use the inline where clause but you can do it your way with a parameter. Is this what you are looking for?
Related
After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................
I am building an SQLite DB. One of the tables consists of 2 columns - term and definition.
My question is : How can I query the DB, in order the pair term-definition to be returned in order to be able to insert the data in the activity after that (the term and data are in ExpandableListView, the term is the Key, the data - the value).
Here is the code of the data source so far:
public class TermDataSource extends DAO {
//constants
public static final String TABLE_NAME = "terms";
public static final String TERM = "term";
public static final String DEFINITION = "definition";
//columns in the table
public static final int FIELD_ID_ID = 0;
public static final int FIELD_ID_TERM = 1;
public static final int FIELD_ID_DEFINITION = 2;
public TermDataSource (Context context){
super(context);
}
private String [] selectFields = {_ID, TERM, DEFINITION};
public Cursor getTermsData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
return cursor;
}
public List<Term> getTerms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
List<Term> terms = new ArrayList<Term>();
if(cursor!=null){
Term term = null;
while(cursor.moveToNext()){
term = getTermFromCursor(cursor);
terms.add(term);
}
cursor.close();
}
db.close();
return terms;
}
private Term getTermFromCursor (Cursor cursor){
Term term = new Term();
term.setTermId(cursor.getInt(FIELD_ID_ID));
term.setTerm(cursor.getString(FIELD_ID_TERM));
term.setDefinition(cursor.getString(FIELD_ID_DEFINITION));
return term;
}
}
Create a folder res>raw and put youfile.csv in that folder.
Use this method to insert data in Your Database from CSV file.
public void insertCSVData(Activity activity, InputStream is, String tableName) {
String colunmNames = null, str1 = null;
open();
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line = "";
String str2 = ");";
db.beginTransaction();
int i = 0;
while ((line = buffer.readLine()) != null) {
i++;
if (i == 1) {
colunmNames = line;
str1 = "INSERT INTO " + tableName + " (" + colunmNames + ") values (";
} else {
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
for (int h = 0; h < str.length; h++) {
if (h == str.length - 1) {
sb.append("'" + str[h] + "'");
} else {
sb.append("'" + str[h] + "',");
}
}
sb.append(str2);
db.execSQL(sb.toString());
}
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (Exception e) {
close();
e.printStackTrace();
}
close();
}
Call this method by the below code :
insertCSVData(Activity.this, getResources().openRawResource(R.raw.yourfile),"Your Table Name");
Can somebody tell me how to make my database not to be empty after restarting application:
Now, It it empty when I`m restarting it. But I need to preserve data, that Im inserting.
I`ve tryed already to aske this question, but nobody told me my mistake.
Here`s my code:
public class DataBaseFactory {
private SQLiteDatabase db;
private final Context context;
private SD_util sdUtil;
private static String DB_NAME = "nyam_db.db3";
private static String DB_PATH = "/data/data/com.st.nyam/databases/";
private static String TAG = "DataBaseFactory";
private static int DATABASE_VERSION = 1;
// private final String INSERT_RECEPY =
// "INSERT into RECEPIES ('id', 'recepy', 'author') VALUES (?, ?, ?)";
private final String SELECT_RECIPES = "SELECT * FROM recipes";
private final String SELECT_RECIPE_BY_ID = "SELECT * FROM recipes WHERE ID = ?";
private final String SELECT_COUNT_RECIPE_BY_ID = "SELECT count(*) FROM recipes WHERE ID = ?";
private final String SELECT_STEPS = "SELECT * FROM steps";
private final String SELECT_TABLES = "SELECT name FROM sqlite_master WHERE type= 'table' ORDER BY name";
private final String SELECT_STEPS_BY_ID = "SELECT * FROM steps where recipe_id = ?";
private final String INSERT_STEP = "INSERT INTO steps ('id', 'recipe_id', 'body', 'photo_file_name') VALUES (?,?,?,?) ";
private final String INSERT_RECIPE = "INSERT INTO recipes ('id', 'title', 'description', 'user_id', 'favorites_by', 'main_photo_file_name') VALUES (?,?,?,?,?,?) ";
private final String DELETE_RECIPE = "DELETE FROM recipes WHERE id = ?";
private final String DELETE_STEPS_BY_RECIPEID = "DELETE FROM steps WHERE recipe_id = ?";
public DataBaseFactory(Context ctx) {
context = ctx;
sdUtil = new SD_util();
SQLiteDatabase temp_db = ctx.openOrCreateDatabase(DB_NAME,
Context.MODE_PRIVATE, null);
temp_db.close();
try {
Log.i(TAG, "Copy intenting");
copyDataBase();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Log.i(TAG, "Temp created");
if (db == null) {
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
SQLiteDatabase.OPEN_READWRITE);
}
Log.i(TAG, "Temp opened");
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
e.printStackTrace();
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open("db/" + 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);
}
Log.i(TAG, "Copy data");
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public ArrayList<RecipeGeneral> getRecipes() {
ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
Cursor c = db.rawQuery(SELECT_RECIPES, null);
Log.d(TAG, "getRecipes()");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting recipe");
RecipeGeneral recipe = ModelUtil.getRecipeFromCursor(c);
recipes.add(recipe);
Log.d(TAG, "Getting recipe added");
} while (c.moveToNext());
}
c.close();
return recipes;
}
public ArrayList<Step> getStepsByRecipeId(int recipeId)
throws ParseException {
Log.d(TAG, "In getStepsByRecipe");
ArrayList<Step> steps = new ArrayList<Step>();
Cursor c = db.rawQuery(SELECT_STEPS_BY_ID,
new String[] { Integer.toString(recipeId) });
Log.d(TAG, "Get Query getStepsByRecipe");
try {
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting step getStepsByRecipe");
Step step = ModelUtil.getStepFromCursor(c);
steps.add(step);
Log.d(TAG, "Getting step added getStepsByRecipe");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
c.close();
return steps;
}
/*
* public ArrayList<Step> getSteps() throws ParseException { ArrayList<Step>
* steps = new ArrayList<Step>(); Cursor c = db.rawQuery(SELECT_STEPS,
* null); if (c != null && c.getCount() > 0) { c.moveToFirst(); do { Step
* step = new Step(); step.setId(c.getInt(c.getColumnIndex("id")));
* step.setRecipe_id(c.getInt(c.getColumnIndex("recipe_id")));
* step.setBody(c.getString(c.getColumnIndex("body")));
* step.setPhoto_file_name
* (c.getString(c.getColumnIndex("photo_file_name")));
* step.setPhoto_content_type
* (c.getString(c.getColumnIndex("photo_content_type")));
* step.setPhoto_file_size(c.getInt(c.getColumnIndex("photo_file_size")));
* step.setPhoto_updated_at(new
* SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse
* (c.getString(c.getColumnIndex("photo_updated_at"))));
* step.setCreated_at(new
* SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString
* (c.getColumnIndex("created_at")))); step.setUpdated_at(new
* SimpleDateFormat
* ("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex
* ("updated_at"))));
* step.setPhoto_processing(c.getInt(c.getColumnIndex("photo_processing")));
* steps.add(step); } while (c.moveToNext()); } c.close(); return steps; }
*/
public ArrayList<Recipe> fetchRecipesByQuery(String query)
throws ParseException {
ArrayList<Recipe> recipes = new ArrayList<Recipe>();
Cursor c = db.query(true, "virt", null, "description " + " Match "
+ "'*" + query + "*'", null, null, null, null, null);
try {
Log.i(TAG, "Get Query");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.i(TAG, "Getting recipe");
// Recipe recipe = ModelUtil.getRecipeFromCursor(c);
// recipes.add(recipe);
Log.i(TAG, "Getting recipe added");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
return recipes;
}
public void addRecipeToFavorites(Recipe recipe, Bitmap bitmap) {
Log.d(TAG, "addRecipeToFavorites begin");
if (!isRecipeExists(recipe.getId())) {
ArrayList<Step> steps = recipe.getSteps();
Log.d(TAG, "Adding recipe to favorites addRecipeToFavorites()");
sdUtil.saveRecipeImage(bitmap, recipe.getImg_url());
db.execSQL(
INSERT_RECIPE,
new String[] { Integer.toString(recipe.getId()),
recipe.getTitle(), recipe.getDescription(),
recipe.getUser(),
Integer.toString(recipe.getFavorites_by()),
recipe.getImg_url() });
if (recipe.getSteps() != null) {
for (Step step : steps) {
Object[] params = new Object[] { step.getImg_url() };
new DownloadImageStep().execute(params);
Log.d(TAG, "Adding step to favorites addRecipeToFavorites()");
addStepToFavorites(step, recipe.getId());
}
} else {
Log.d(TAG, "No steps in this recipe");
}
} else {
Log.d(TAG, "Recipe already added");
}
}
private void addStepToFavorites(Step step, int recipe_id) {
db.execSQL(
INSERT_STEP,
new String[] { Integer.toString(step.getNumber()),
Integer.toString(recipe_id), step.getInstruction(),
step.getImg_url(), });
}
public void deleteRecipeFromFavorites(Recipe recipe) {
Log.d(TAG, "deleteRecipeFromFavorites begin");
if (isRecipeExists(recipe.getId())) {
if (recipe.getSteps() != null) {
for (Step step : recipe.getSteps()) {
Log.d(TAG, "Boolean stepimage deleted = " + sdUtil.deleteImageFromSD(step.getImg_url().replace('/', '&')));
}
deleteStepsFromFavoritesByRecipeId(recipe.getId());
} else {
Log.d(TAG, "No steps in this recipe");
}
Log.d(TAG, "Image name in database = " + recipe.getImg_url().replace('/', '&'));
Log.d(TAG, "Boolean recipeimage deleted = " + sdUtil.deleteImageFromSD(recipe.getImg_url().replace('/', '&')));
Log.d(TAG, "Deleted rows: " + db.delete("recipes", "id=?", new String[] {Integer.toString(recipe.getId())}));
} else {
Log.d(TAG, "Recipe doesn`t exist");
}
}
private void deleteStepsFromFavoritesByRecipeId(int recipeId) {
Log.d(TAG, "deleteStepsFromFavoritesByRecipeId begin");
db.delete("steps", "recipe_id=?", new String[] { Integer.toString(recipeId)});
}
/*
* public void putRecepy(Recepy recepy) { db.execSQL(INSERT_RECEPY, new
* String[] {Integer.toString(recepy.getId()), recepy.getRecepy(),
* recepy.getAuthor()}); }
*/
public boolean isRecipeExists(int id) {
Cursor c = db.rawQuery(SELECT_RECIPE_BY_ID,
new String[] { Integer.toString(id) });
try {
Log.d(TAG, "isRecipeExists before c.movetoFirst()");
if (c.moveToFirst()) {
if (c != null && c.getCount() > 0) {
Log.d(TAG, "Checking passed");
//Recipe recipe = ModelUtil.getRecipeFromCursor(c);
//Log.d(TAG, "RECIPEExists: " + recipe.toString());
return true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return false;
}
private class DownloadImageStep extends AsyncTask<Object, Void, Object> {
#Override
protected Object doInBackground(Object... o) {
Bitmap outBitmap = null;
try {
sdUtil.saveStepImage((String) o[0]);
} catch (Exception e) {
e.printStackTrace();
}
return outBitmap;
}
}
}
UPDATED:
I found my mistake. It is in constructor. I don`t have to create temp_db and invoke copyData();
I found my mistake. It is in constructor. I don`t have to create temp_db and invoke copyData();
I have an issue. My database becomes empty after 'Force stop'.
Initially I open empty database, then I`m adding some data. Then I see them in database, they are can be seen in program. But if I restart phone or make "Force stop" of application - everything starts from the very begining.
Here`s my code of DataBaseFactory:
package com.st.nyam.factories;
public class DataBaseFactory {
private SQLiteDatabase db;
private final Context context;
private SD_util sdUtil;
private static String DB_NAME = "nyam_db.db3";
private static String DB_PATH = "/data/data/com.st.nyam/databases/";
private static String TAG = "DataBaseFactory";
//private final String INSERT_RECEPY = "INSERT into RECEPIES ('id', 'recepy', 'author') VALUES (?, ?, ?)";
private final String SELECT_RECIPES = "SELECT * FROM recipes";
private final String SELECT_RECIPE_BY_ID = "SELECT * FROM recipes WHERE ID = ?";
private final String SELECT_COUNT_RECIPE_BY_ID = "SELECT count(*) FROM recipes WHERE ID = ?";
private final String SELECT_STEPS = "SELECT * FROM steps";
private final String SELECT_TABLES = "SELECT name FROM sqlite_master WHERE type= 'table' ORDER BY name";
private final String SELECT_STEPS_BY_ID = "SELECT * FROM steps where recipe_id = ?";
private final String INSERT_STEP = "INSERT INTO steps ('id', 'recipe_id', 'body', 'photo_file_name') VALUES (?,?,?,?) ";
private final String INSERT_RECIPE = "INSERT INTO recipes ('id', 'title', 'description', 'user_id', 'favorites_by', 'main_photo_file_name') VALUES (?,?,?,?,?,?) ";
public DataBaseFactory(Context ctx) {
context = ctx;
sdUtil = new SD_util();
SQLiteDatabase temp_db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
temp_db.close();
try {
Log.i(TAG, "Copy intenting");
copyDataBase();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Log.i(TAG, "Temp created");
if (db == null) {
db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
}
Log.i(TAG, "Temp opened");
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch(SQLiteException e){
//database does't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = context.getAssets().open("db/" + 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);
}
Log.i(TAG, "Copy data");
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public ArrayList<RecipeGeneral> getRecipes() {
ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
Cursor c = db.rawQuery(SELECT_RECIPES, null);
Log.d(TAG, "getRecipes()");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting recipe");
RecipeGeneral recipe = ModelUtil.getRecipeFromCursor(c);
recipes.add(recipe);
Log.d(TAG, "Getting recipe added");
} while (c.moveToNext());
}
c.close();
return recipes;
}
public ArrayList<Step> getStepsByRecipeId(int recipeId) throws ParseException {
Log.d(TAG, "In getStepsByRecipe");
ArrayList<Step> steps = new ArrayList<Step>();
Cursor c = db.rawQuery(SELECT_STEPS_BY_ID, new String[]{ Integer.toString(recipeId) });
Log.d(TAG, "Get Query getStepsByRecipe");
try {
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.d(TAG, "Getting step getStepsByRecipe");
Step step = ModelUtil.getStepFromCursor(c);
steps.add(step);
Log.d(TAG, "Getting step added getStepsByRecipe");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
c.close();
return steps;
}
/*
public ArrayList<Step> getSteps() throws ParseException {
ArrayList<Step> steps = new ArrayList<Step>();
Cursor c = db.rawQuery(SELECT_STEPS, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Step step = new Step();
step.setId(c.getInt(c.getColumnIndex("id")));
step.setRecipe_id(c.getInt(c.getColumnIndex("recipe_id")));
step.setBody(c.getString(c.getColumnIndex("body")));
step.setPhoto_file_name(c.getString(c.getColumnIndex("photo_file_name")));
step.setPhoto_content_type(c.getString(c.getColumnIndex("photo_content_type")));
step.setPhoto_file_size(c.getInt(c.getColumnIndex("photo_file_size")));
step.setPhoto_updated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("photo_updated_at"))));
step.setCreated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("created_at"))));
step.setUpdated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("updated_at"))));
step.setPhoto_processing(c.getInt(c.getColumnIndex("photo_processing")));
steps.add(step);
} while (c.moveToNext());
}
c.close();
return steps;
}
*/
public ArrayList<Recipe> fetchRecipesByQuery(String query) throws ParseException {
ArrayList<Recipe> recipes = new ArrayList<Recipe>();
Cursor c = db.query(true, "virt", null, "description " + " Match " + "'*" + query + "*'", null,
null, null, null, null);
try{
Log.i(TAG, "Get Query");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
do {
Log.i(TAG, "Getting recipe");
//Recipe recipe = ModelUtil.getRecipeFromCursor(c);
//recipes.add(recipe);
Log.i(TAG, "Getting recipe added");
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
return recipes;
}
public void addRecipeToFavorites(Recipe recipe, Bitmap bitmap) {
if (!isRecipeExists(recipe.getId())) {
ArrayList<Step> steps = recipe.getSteps();
Log.d(TAG,"Adding recipe to favorites addRecipeToFavorites()");
sdUtil.saveRecipeImage(bitmap, recipe.getImg_url());
db.execSQL(INSERT_RECIPE, new String[] {
Integer.toString(recipe.getId()), recipe.getTitle(),
recipe.getDescription(), recipe.getUser(),
Integer.toString(recipe.getFavorites_by()), recipe.getImg_url()
});
for (Step step : steps) {
Object [] params = new Object[] {step.getImg_url()};
new DownloadImageStep().execute(params);
Log.d(TAG,"Adding step to favorites addRecipeToFavorites()");
addStepToFavorites(step, recipe.getId());
}
} else {
Log.d(TAG,"Recipe already added");
}
}
public void addStepToFavorites(Step step, int recipe_id) {
db.execSQL(INSERT_STEP, new String[]{
Integer.toString(step.getNumber()), Integer.toString(recipe_id),
step.getInstruction(), step.getImg_url(),
});
}
/*
public void putRecepy(Recepy recepy) {
db.execSQL(INSERT_RECEPY, new String[]
{Integer.toString(recepy.getId()),
recepy.getRecepy(), recepy.getAuthor()});
}
*/
public boolean isRecipeExists(int id) {
Cursor c = db.rawQuery(SELECT_RECIPE_BY_ID, new String[]
{Integer.toString(id)});
try {
Log.d(TAG, "isRecipeExists before c.movetoFirst()");
if (c.moveToFirst()) {
if (c != null && c.getCount() > 0) {
Log.d(TAG, "Checking passed");
//Recipe recipe = ModelUtil.getRecipeFromCursor(c);
//Log.d(TAG, "RECIPEExists: " + recipe.toString());
return true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return false;
}
private class DownloadImageStep extends AsyncTask<Object,Void,Object> {
#Override
protected Object doInBackground(Object... o) {
Bitmap outBitmap = null;
try{
sdUtil.saveStepImage((String)o[0]);
}
catch(Exception e){
e.printStackTrace();
}
return outBitmap;
}
}
}
Override the onUpgrade() Method of the SQLiteOpenHelper class and make sure it is empty. That is the place where your database might have been deleted.
I need to display data from 4 different database tables in android. Previously for testing I used single table to display data. For that I have created three files.
1)DBAdapter.java
2)UserBO.java
3)Test.java
DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "mydb.sqlite";
private SQLiteDatabase myDataBase1;
private final Context myContext1;
private static DBAdapter mDBConnection;
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext1 = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
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;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext1.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 {
String myPath = DB_PATH + DB_NAME;
myDataBase1 = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (myDataBase1 != null)
myDataBase1.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase1.rawQuery(query, selectionArgs);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
**UserBO.java**
public class UserBO {
int sid;
String sname;
public int getsid() {
return sid;
}
public void setsid(int sid) {
this.sid = sid;
}
public String getsname() {
return sname;
}
public void setsname(String sname) {
this.sname= sname;
}
}
Test.java
public class Select extends Activity {
private Header header;
private ListView lvUsers;
private ArrayList<UserBO> mListUsers;
private SharedPreferences mPreferences1;
private SharedPreferences mPreferences2;
String myString1,query;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("before k select "+k);
setContentView(R.layout.select);
header = (Header) findViewById(R.id.layoutHeader);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
lvUsers.setAdapter(new ListAdapter(this, R.id.lv_user, mListUsers));
}
public ArrayList<UserBO> getUsers(){
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
mPreferences1 = getSharedPreferences("CurrentUser1", 0);
myString1 = mPreferences1.getString("student id",sid);
dbAdapter.openDataBase();
**query="SELECT tabel1.*, tabel2.* FROM tabel1, tabel2 WHERE tabel1.PK=tabel2.FK;";**
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
AppConstants.alConductedQuestions.add(user);
System.out.println("mListUsers");
System.out.println(user);
try {
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
}
catch (Exception e) {
Log.i("***" + Test.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> { // --CloneChangeRequired
private ArrayList<UserBO> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
//System.out.println(list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting list_item views
( (TextView) view.findViewById(R.id.casedescription) ).setText( listItem.getsid()+"");
( (TextView) view.findViewById(R.id.tv_question) ).setText( listItem.getsname()+"");
ArrayList<UserBO> mList1;
}
}
catch(Exception e){
String err = (e.getMessage()==null)?"hii":e.getMessage();
Log.e("sdcard-err2:",err);
}
return view;
}
}
}
In test.java I am writing the query. In UserBO I am writing the setter and getter methods. In DBAdapter file I am mentioning the database name. So here my question is I have 4 tables in my database. So I need to display data using those tables. Shall I write the setter and getter methods of the column names of all the tables in one single UserBO file?
Also I am getting the values of each column of single table by giving
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
*How do I get the column names of all the tables?* I mean shall I need to get all the columns of all the tables in Test.java file?
Please help me regarding this....I am it confused with this different tables.....
Thanks in Advance
you have one database & three tables or all three tables are in different databsaes ?