update row by id, cannote resolve sqlite update method - android

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

Related

Display each row from Database on a new line in a TextView

I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}

Listview for SQL lite

I was following a school tutorial for sql lite, and the output was a list of buttons. Is it possible to output this to a ListView instead?
I've tried googling and youtube but somehow the tutorial I was following seems to have more files?
Confused newbie here!
Thanks in advance!
This code appears in the onCreate(Bundle savedInstanceState)
private void ShowExistingIdeas() {
Idea[] ideas = new Ideas(this).getAllIdeas();
if(ideas != null && ideas.length > 0)
{
for(int index = 0; index < ideas.length; index++)
{
Button ideaButton = new Button(this);
ideaButton.setText(ideas[index].getTitle());
final int id = ideas[index].getId();
ideaButton.setTag(id);
ideaButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(OverviewActivity.this,
EditIdeaActivity.class);
i.putExtra("id", id);
startActivityForResult(i, 0);
}
});
//!!! The bit I'm trying to change. the xml with LinearLayout1 is completely empty****
((LinearLayout) findViewById(R.id.LinearLayout1)).
addView(ideaButton);
}
}
}
For your reference - the Ideas file
public class Ideas {
private Idea[] ideas;
private Context context;
public Ideas(Context context) {
this.context = context;
}
public Idea[] getAllIdeas() {
return getIdeasWithKeyword(null);
}
public Idea[] getIdeasWithKeyword(String keyword) {
ideas = null;
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
String where = null;
String[] whereArgs = null;
if (keyword != null) {
where = DbHelper.COL_TITLE + " LIKE '%?%' OR " + DbHelper.COL_DESC
+ " LIKE '%?%'";
whereArgs = new String[] { keyword };
}
Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, where,
whereArgs, null, null, null);
if (c != null && c.moveToFirst()) {
ideas = new Idea[c.getCount()];
boolean hasMore = true;
for (int index = 0; hasMore; hasMore = c.moveToNext(), index++) {
int id = c.getInt(c.getColumnIndex(DbHelper.COL_ID));
String title = c
.getString(c.getColumnIndex(DbHelper.COL_TITLE));
String description = c.getString(c
.getColumnIndex(DbHelper.COL_DESC));
int priority = c
.getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));
ideas[index] = new Idea(id, title, description, priority);
}
}
if (db != null && db.isOpen())
db.close();
return ideas;
}
public Idea getIdea(int id) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
Cursor c = db.query(DbHelper.TABLE_IDEAS, DbHelper.COLUMNS, "_id = "
+ id, null, null, null, null);
Idea idea = null;
if (c != null && c.moveToFirst()) {
String title = c.getString(c.getColumnIndex(DbHelper.COL_TITLE));
String description = c.getString(c
.getColumnIndex(DbHelper.COL_DESC));
int priority = c.getInt(c.getColumnIndex(DbHelper.COL_PRIORITY));
idea = new Idea(id, title, description, priority);
}
if (db != null && db.isOpen())
db.close();
return idea;
}
public void addIdea(Idea idea) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DbHelper.COL_TITLE, idea.getTitle());
values.put(DbHelper.COL_DESC, idea.getDescription());
values.put(DbHelper.COL_PRIORITY, idea.getPriority());
db.insert(DbHelper.TABLE_IDEAS, null, values);
if (db != null && db.isOpen())
db.close();
}
public void deleteIdea(int ideaId) {
SQLiteDatabase db = new DbHelper(context).getWritableDatabase();
db.delete(DbHelper.TABLE_IDEAS, DbHelper.COL_ID + "=" + ideaId, null);
if (db != null && db.isOpen())
db.close();
}
}

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 SQLiteDatabase empty after restart of app

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

using sqlite in BroadcastReceiver

I want perform a easy task in android, which when receiving a call the phonenumber will be matched to a number in my database. However I already read that sqlite and BroadcastReceiver are not that easy to combine. Below is the code:
public class incomingcall extends BroadcastReceiver{
String caller;
Cursor c;
#Override
public void onReceive(Context context, Intent intent) {
sqlitedatabase search = new sqlitedatabase(context);
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
Log.i("IncomingCallReceiver",bundle.toString());
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
Log.i("IncomingCallReceiver","State: "+ state);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
{
String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("IncomingCallReceiver","Incomng Number: " + phonenumber);
try{
search.open();
c = search.callinfo(phonenumber);
if(c != null){
int iFN = c.getColumnIndex("firstname");
int iLN = c.getColumnIndex("lastname");
String FN = c.getString(iFN);
String LN = c.getString(iLN);
caller = FN + " " + LN;
}
else{
caller = "Unknown";
}
search.close();
}
catch (Exception e){
Toast.makeText(context, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
Toast.makeText(context, caller, Toast.LENGTH_LONG).show();
}
}
}
I don't think the problem lies with the methode ".callinfo()", nonetheless I posted it below:
public Cursor callinfo(String l) {
// TODO Auto-generated method stub
String[] columns = new String[]{"phonenumber", "homenumber"};
Cursor c = db.query("mycontacts", columns, "phonenumber = " + l + " OR " + "homenumber = " + l, null, null, null, null);
return c;
}
The Catch returns : errorandroid.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1.
Thank you in advance for any help you can give me.
Cheers
Because the initial cursor position is -1, try to use if(c.moveToNext()) instead of if(c != null).

Categories

Resources