Android SQLiteDatabase empty after restart of app - android

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();

Related

Model object is not matching with the database result

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))));
....................................................

update row by id, cannote resolve sqlite update method

I need to update a row of my database, but I get an error with SQLiteDatabase update method not resolved.
I think this is because of the custom class I had to create:
public class DBAccess {
public static String LOG_TAG = "DBAccess";
private SQLiteDatabase database;
private DBHelper dbHelper;
public DBAccess(Context context) {
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Integer saveVehicle (Vehicle v){
Integer id = null;
if(this.database.isOpen() && !this.database.isReadOnly()){
String queryInsert = DBHelper.QueryAccessoAlDato.INSERT_VEHICLE;
try{
this.database.execSQL(queryInsert, new Object[]{v.getManufacturer(), v.getModel(), v.getPlate(),
v.getKmAmount(), v.getPrezzoGiorno(), v.getPrezzoSettimana(), v.getPrezzoMese(), v.getFuel(),
v.getGruppoMacchina()});
}catch (SQLException e){
Log.e(LOG_TAG, "Si รจ verificato un errore in inserimento " + e.getMessage());
e.printStackTrace();
return null;
}
Then this is the OnClick method of the main activity:
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "Marca: "+this.etManufacturer.getText());
Log.d(LOG_TAG, "Modello: "+this.etModel.getText());
Log.d(LOG_TAG, "Targa: "+this.etPlate.getText());
Log.d(LOG_TAG, "Kilometraggio: "+this.etKmAmount.getText());
Log.d(LOG_TAG, "PrezzoGiorno: "+this.etPrezzoGiorno.getText());
Log.d(LOG_TAG, "PrezzoSettimana: "+this.etPrezzoSettimana.getText());
Log.d(LOG_TAG, "PrezzoMese: "+this.etPrezzoMese.getText());
Log.d(LOG_TAG, "Fuel: "+this.etFuel.getText());
Log.d(LOG_TAG, "Gruppo Macchina: "+this.etGruppoMacchina.getText());
if(!(this.etManufacturer.getText().length() == 0) &&
!(this.etModel.getText().length() == 0) &&
!(this.etPlate.getText().length() == 0) &&
!(this.etKmAmount.getText().length() == 0) &&
!(this.etPrezzoGiorno.getText().length() == 0) &&
!(this.etPrezzoSettimana.getText().length() == 0) &&
!(this.etPrezzoMese.getText().length() == 0) &&
!(this.etFuel.getText().length() == 0) &&
!(this.etGruppoMacchina.getText().length() == 0)
){
Vehicle myVehicle = null;
String manufacturer = this.etManufacturer.getText().toString();
String model = this.etModel.getText().toString();
String plate = this.etPlate.getText().toString();
long KmAmount = Long.parseLong(this.etKmAmount.getText().toString());
int prezzoGiorno = Integer.parseInt(etPrezzoGiorno.getText().toString());
int prezzoSettimana = Integer.parseInt(etPrezzoSettimana.getText().toString());
int prezzoMese = Integer.parseInt(etPrezzoMese.getText().toString());
String fuel = this.etFuel.getText().toString();
String gruppoMacchina = this.etGruppoMacchina.getText().toString();
myVehicle = new Vehicle (manufacturer, model, plate, KmAmount, prezzoGiorno,
prezzoSettimana, prezzoMese,fuel, gruppoMacchina);
Log.d(LOG_TAG, "Hai aggiunto " + myVehicle + "con id" + vehicleID);
DBAccess dba = new DBAccess(this.getApplicationContext());
dba.open();
Log.d(LOG_TAG, "Avvio lettura da db");
if (this.getIntent().hasExtra(Const.ID_VEHICLE)) {
//http://stackoverflow.com/questions/9798473/sqlite-in-android-how-to-update-a-specific-row
ContentValues values= new ContentValues();
values.put(DBHelper.VEHICLE_MANUFACTORER_COLUMN, manufacturer);
values.put(DBHelper.VEHICLE_MODEL_COLUMN, model);
//values.put(DBHelper.KEY_PEDLOCATION, ped_location);
// values.put(DBHelper.KEY_PEDEMAIL, ped_emailid);
// etc etc
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
finish();
}else{
dba.saveVehicle(myVehicle);
Log.d(LOG_TAG, "Ho salvato" + myVehicle);
dba.close();
finish();
So i get the error at line :
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
How can I resolve this? Thank you!
First your DBAccess class should extend SQLiteOpenHelper class.
The Update method declaration is as below, the last parameter should be a String array,
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Change your code to as shown below:
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=?", new String[]{String.valueOf(vehicleID));

Getting a unique row in SQLite

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?

Application stops working on mobile device but runs on emmulator

i have developed an app for 'bank simulation' which uses sqlite to create databases...
when i run the app on my mobile it stops unexpectedly....do i need to install any server to run sqlite based apps on mobile?
Thanks in advance!
DbHelper.java
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SUBH_TABLE_NAME = "login";
public static final String SUBH_TABLE_DATA = "TBL_Transaction";
public static final String KEY_ROWID = "_id";
private static final String SUBH_TABLE_CREATE =
"CREATE TABLE " + SUBH_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, balance INTEGER);";
private static final String SUBH_TABLE_DATA_CREATE =
"CREATE TABLE " + SUBH_TABLE_DATA + "(" +
"trans_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
"user_id INTEGER, " +
"trans TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO "+ SUBH_TABLE_NAME +" values(1, admin, password, admin#gmail.com);";
//private static final String SAKET_DB_ADMIN_Trans = "INSERT INTO "+ SUBH_TABLE_DATA +" values(1, asdf);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
try{
//Create Database
db.execSQL(SUBH_TABLE_CREATE);
//create transaction account
db.execSQL(SUBH_TABLE_DATA_CREATE);
//create admin account
db.execSQL(SAKET_DB_ADMIN);
//db.execSQL(SAKET_DB_ADMIN_Trans);
System.out.println("In onCreate");
}catch(Exception e){
e.printStackTrace();
}
}
DatabaseActivity.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNewUser = (Button) findViewById(R.id.buttonNewUser);
mNewUser.setOnClickListener(this);
mLogin = (Button) findViewById(R.id.buttonLogin);
mLogin.setOnClickListener(this);
mShowAll = (Button) findViewById(R.id.buttonShowAll);
mShowAll.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonLogin:
mUsername = (EditText) findViewById(R.id.editUsername);
mPassword = (EditText) findViewById(R.id.editPassword);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if (uname.equals("") || uname == null) {
Toast.makeText(getApplicationContext(), "Username Empty",
Toast.LENGTH_SHORT).show();
} else if (pass.equals("") || pass == null) {
Toast.makeText(getApplicationContext(), "Password Empty",
Toast.LENGTH_SHORT).show();
} else {
boolean validLogin = false;
try {
validLogin = validateLogin(uname, pass,
DatabaseActivity.this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (validLogin) {
System.out.println("In Valid");
Intent i_login = new Intent(DatabaseActivity.this,
UserLoggedInPage.class);
try {
id = getID(uname, pass, DatabaseActivity.this);
Ubal = getBAL(uname, pass, DatabaseActivity.this);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "putting the extra " + id);
i_login.putExtra("key", id);
i_login.putExtra("bkey", Ubal);
startActivity(i_login);
finish();
}
}
break;
case R.id.buttonNewUser:
Intent i = new Intent(DatabaseActivity.this, NewUserActivity.class);
startActivity(i);
finish();
break;
case R.id.buttonShowAll:
Intent i_admin = new Intent(DatabaseActivity.this, AdminPage.class);
startActivity(i_admin);
finish();
break;
}
}
public boolean validateLogin(String uname, String pass, Context context)
throws Exception {
myDb = new DbHelper(context);
SQLiteDatabase db = myDb.getReadableDatabase();
// SELECT
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = null;
try {
// SELECT _id FROM login WHERE username = uname AND password=pass
cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
startManagingCursor(cursor);
} catch (Exception e) {
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if (numberOfRows <= 0) {
Toast.makeText(getApplicationContext(),
"Login Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
// get rowid
// public int getID(String uname, String pass, Context context)
// throws Exception {
//
// myDb = new DbHelper(context);
// SQLiteDatabase db = myDb.getReadableDatabase();
// cursor = db.rawQuery("select * from " + DbHelper.SUBH_TABLE_NAME +
// " where username = " + uname + "&" + "password = " + pass + ";)", null);
// if (cursor != null) {
// if(cursor.moveToFirst()){
// int id = cursor.getInt(cursor.getColumnIndex(DbHelper.KEY_ROWID));
// }
//
// }
//
// return id;
//
// }
public String getID(String uname, String pass, Context context) {
try {
String idddd = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
idddd = cursor.getString(0);
}
return idddd;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getBAL(String uname, String pass,
DatabaseActivity databaseActivity) {
try {
String ballll = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "balance" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
ballll = cursor.getString(0);
}
return ballll;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onDestroy() {
super.onDestroy();
if (myDb != null && cursor != null ) {
cursor.close();
myDb.close();
}
}
}

Android database becomes empty after 'Force stop'

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.

Categories

Resources