No such column Exception using getContentResolver().update - java

I have the following method for updating only the COL_COUNT(originally set to 1) of an existing record "tag" in database:
public void addCount(){
mFtag = "tag";
String t = "2";
ContentValues values = new ContentValues();
values.put(FTagsContentProvider.COL_COUNT, t );
getContentResolver().update(FTagsContentProvider.CONTENT_URI, values, "COL_TEXT=?", new String[]{mFtag});
}
When I run it I got the following exception:
I tried changing the line
getContentResolver().update(FTagsContentProvider.CONTENT_URI, values, "COL_TEXT=?", new String[]{mFtag});
to
getContentResolver().update(FTagsContentProvider.CONTENT_URI, values, FTagsContentProvider.COL_TEXT + "=?", new String[]{mFtag});
Still same exception just change from "no such column: COL_TEXT" to "no such column: tag"
Here is the ContentProvider:
public class FTagsContentProvider extends ContentProvider {
static final String AUTHORITY = "ch.ethz.twimight.FTags";
private static final String BASE_PATH = "ftags";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
// fields for the database
public static final String COL_ID = "id";
public static final String COL_TEXT = "text";
public static final String COL_COUNT = "count";
static final int FTAGS = 1;
static final int FTAGS_ID = 2;
DBHelper dbHelper;
private static HashMap<String, String> FTagsMap;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, BASE_PATH, FTAGS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", FTAGS_ID);
}
// database declarations
private SQLiteDatabase database;
static final String DATABASE_NAME = "ftagtable.db";
static final String TABLE_FTAGS = "FTags";
static final int DATABASE_VERSION = 1;
private static final String TABLE_FTAGS_CREATE = "create table "
+ TABLE_FTAGS
+ "("
+ COL_ID + " integer primary key autoincrement, "
+ COL_TEXT + " text not null, "
+ COL_COUNT + " integer"
+ ");";
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(TABLE_FTAGS_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ". Old data will be destroyed");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FTAGS);
onCreate(db);
}
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
Context context = getContext();
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
if(database == null)
return false;
else
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_FTAGS);
switch (uriMatcher.match(uri)) {
case FTAGS:
queryBuilder.setProjectionMap(FTagsMap);
break;
case FTAGS_ID:
queryBuilder.appendWhere( COL_ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == ""){
sortOrder = COL_TEXT;
}
Cursor cursor = queryBuilder.query(database, projection, selection,
selectionArgs, null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
long row = database.insert(TABLE_FTAGS, "", values);
if(row > 0) {
Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Fail to add a new record into " + uri);
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
int rowsUpdated = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
rowsUpdated = database.update(TABLE_FTAGS, values, selection, selectionArgs);
break;
case FTAGS_ID:
rowsUpdated = database.update(TABLE_FTAGS, values, COL_ID +
" = " + uri.getLastPathSegment() +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
int count = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
count = database.delete(TABLE_FTAGS, selection, selectionArgs);
break;
case FTAGS_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete( TABLE_FTAGS, COL_ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
Is it a problem with the method or there is something wrong with the ContentProvider? Please help

getContentResolver().update(FTagsContentProvider.CONTENT_URI, values, FTagsContentProvider.COL_TEXT + "=?", new String[]{mFtag});
is the correct usage.
public static final String COL_TEXT = "text";
text is a reserved keyword. You can't have a column named text. Change the name of the column and you'll be fine.

Related

How to keep count of the times an existing record being inserted in database?

I am totally new in this and I am sure I screwed the code somehow, please help me fix it.
I have the following contentprovider for building a database to store favourite tags:
public class FTagsContentProvider extends ContentProvider {
static final String AUTHORITY = "ch.ethz.twimight.FTags";
private static final String BASE_PATH = "ftags";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
// fields for the database
public static final String COL_ID = "id";
public static final String COL_TEXT = "text";
public static final String COL_COUNT = "count";
static final int FTAGS = 1;
static final int FTAGS_ID = 2;
DBHelper dbHelper;
private static HashMap<String, String> FTagsMap;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, BASE_PATH, FTAGS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", FTAGS_ID);
}
// database declarations
private SQLiteDatabase database;
static final String DATABASE_NAME = "ftagtable.db";
static final String TABLE_FTAGS = "FTags";
static final int DATABASE_VERSION = 1;
private static final String TABLE_FTAGS_CREATE = "create table "
+ TABLE_FTAGS
+ "("
+ COL_ID + " integer primary key autoincrement, "
+ COL_TEXT + " text not null, "
+ COL_COUNT + " integer"
+ ");";
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(TABLE_FTAGS_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ". Old data will be destroyed");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FTAGS);
onCreate(db);
}
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
Context context = getContext();
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
if(database == null)
return false;
else
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_FTAGS);
switch (uriMatcher.match(uri)) {
case FTAGS:
queryBuilder.setProjectionMap(FTagsMap);
break;
case FTAGS_ID:
queryBuilder.appendWhere( COL_ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == ""){
sortOrder = COL_TEXT;
}
Cursor cursor = queryBuilder.query(database, projection, selection,
selectionArgs, null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
long row = database.insert(TABLE_FTAGS, "", values);
if(row > 0) {
Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Fail to add a new record into " + uri);
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
int rowsUpdated = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
rowsUpdated = database.update(TABLE_FTAGS, values, selection, selectionArgs);
break;
case FTAGS_ID:
rowsUpdated = database.update(TABLE_FTAGS, values, COL_ID +
" = " + uri.getLastPathSegment() +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
int count = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
count = database.delete(TABLE_FTAGS, selection, selectionArgs);
break;
case FTAGS_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete( TABLE_FTAGS, COL_ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
I want to set the COL_COUNT as a value of keeping count the times that a tag has been inserted into the database, originally it should be 1 for each tag, and I want it to update only the count like from 1 to 2 and so on every time an existing tag is input.
Here is the Activity:
public class TestActivity extends Activity {
private EditText mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
public boolean check(String s){
boolean t = false;
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(FTagsContentProvider.CONTENT_URI,
new String []{FTagsContentProvider.COL_TEXT}, FTagsContentProvider.COL_TEXT + "=?", new String[]{s}, null);
if(cursor.getCount > 0){
t = true;
}
else{
t = false;
}
cursor.close();
return t;
}
public void addFTag(View view) {
// Add a new tag
ContentValues values = new ContentValues();
mText = (EditText)findViewById(R.id.name);
String mFtag = mText.getText().toString();
boolean exist = check(mFtag);
if(exist == false){
values.put(FTagsContentProvider.COL_TEXT,
mFtag);
Uri uri = getContentResolver().insert(
FTagsContentProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(),
"Record inserted!", Toast.LENGTH_LONG).show();
}
else{
// code for only updating the COL_COUNT somehow
Toast.makeText(this, "Some tag meet you again :)",
Toast.LENGTH_LONG).show();
}}
public void showAllTags(View view) {
Cursor c = getContentResolver().query(FTagsContentProvider.CONTENT_URI, null, null, null, null);
String result = "Results:";
if (!c.moveToFirst()) {
Toast.makeText(this, result+" no content yet!", Toast.LENGTH_LONG).show();
}else{
do{
result = result + "\n" + c.getString(c.getColumnIndex(FTagsContentProvider.COL_TEXT)) +
" with id " + c.getString(c.getColumnIndex(FTagsContentProvider.COL_ID)) +
" has count: " + c.getString(c.getColumnIndex(FTagsContentProvider.COL_COUNT));
} while (c.moveToNext());
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
}
Any help would be much appreciated :)

Populate ListView from SQL using SimpleCursorAdapter

I am trying to populate a ListView with data retrieved from an SQLite Database using a SimpleCursorAdapter. The KEYs that we used for the table are;
_ROWID - for the row number (which should not be visible in the ListView)
_NAME - for the name of a food product in our database (like Bread or Cheese)
_AMOUNT - for the quantity you have of this food product
_DATE - for the expiry date of the product
Another groupmember wrote the code for the database and about halfway through there is a public String called getData. The code looks like this;
public class DatabaseCustom {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DATE = "expiration_date";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_AMOUNT, KEY_DATE};
private static final String DATABASE_NAME = "customDb";
private static final String DATABASE_TABLE = "customTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY_KEY, " + KEY_NAME + " TEXT NOT NULL, "
+ KEY_AMOUNT + " TEXT NOT NULL, " + KEY_DATE
+ "TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseCustom(Context c) {
ourContext = c;
}
public DatabaseCustom open() {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String amount, String date) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_AMOUNT, amount);
cv.put(KEY_DATE, date);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iDate = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iAmount) + " " + c.getString(iDate)
+ "\n";
}
return result;
}
public String getName(long l) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getAmount(long l) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String name = c.getString(2);
return name;
}
return null;
}
public String getDate(long l) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String name = c.getString(3);
return name;
}
return null;
}
public void updateEntry(long lRow, String mName, String mAmount,
String mDate) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_AMOUNT, mAmount);
cvUpdate.put(KEY_DATE, mDate);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow,
null);
}
public void deleteEntry(long lRow1) {
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
From what I gathered I need to set up a populateListView method using a SimpleCursorAdapter in the code for the Activity that shows this ListView. This is the code I have so far (leaving out some code that is irrelevant for my question);
public class Products extends Activity implements OnClickListener{
DatabaseCustom ourDb;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.products);
openDb();
initiate();
populateListView();
}
public void onClick(View v) {
switch (v.getId()){
//A few different buttons for this activity here
}
}
private void initiate(){
//Link all the java variables to the corresponding xml elements here
}
private void openDb(){
ourDb = new DatabaseCustom(this);
ourDb.open();
}
private void populateListView(){
Cursor cursor = ourDb.getData();
String[] fromFieldNames = new String[] {DatabaseCustom.KEY_NAME, DatabaseCustom.KEY_AMOUNT, DatabaseCustom.KEY_DATE};
int[] toViewIDs = new int[] {R.id.tvProductNameList, R.id.tvAmountList, R.id.tvDateList};
SimpleCursorAdapter ourCursorAdapter;
ourCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);//Put text from KEYS into TVs
ListView ourList = (ListView) findViewById(R.id.lvProducts);
ourList.setAdapter(ourCursorAdapter);
}
In the populateListView method I try to create a cursor that looks for the getData method in our database and logicly gives an error as the getData method in this database is a public String and not a public cursor, so I tried to create a public Cursor instead, which I coded as follows;
public Cursor getData() {
String where = null;
Cursor c = ourDatabase.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
After adding the codes for private void populateListView and the public Cursor get Data Eclipse doesn't show any errors, but the application crashes when the activity is loaded that is supposed to show the ListView.
After following numerous tutorials on SQL Databases, ListViews, CursorAdapters and String Arrays, I've come to the point where I'm not sure where to look for answers anymore, so any help would be immensely appreciated.

How to update a specific row in SQLite?

Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? Thank you.
My database code?
package com.example.parkangel;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + "
INTEGER NOT NULL);");
ContentValues values = new ContentValues();
values.put(KEY_PFNAME, "Tutku");
values.put(KEY_PSNAME, "Erbil");
values.put(KEY_CARD, "12345677");
values.put(KEY_CREDITS, 5);
db.insert(DATABASE_TABLE, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname) + " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
public void upDateUser(String money) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, money);
ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
}
}
Class that needs to perform the actoin:
package com.example.parkangel;
public class Balance extends Activity implements OnClickListener{
Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
//db.addUser();
db.close();
tv.setText(data);
ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
add.setOnClickListener(this);
//add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner3.getContext().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
}catch (Exception e){
work = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Unable To TopUp!");
TextView dg = new TextView(this);
dg.setText(error);
d.setContentView(dg);
d.show();
}finally{
if(work){
Dialog d = new Dialog(this);
d.setTitle("You Have ToppedUp!");
TextView dg = new TextView(this);
dg.setText("TopUp Successful");
d.setContentView(dg);
d.show();
}
}
break;
}
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. Parse the value to integer and add "new" money. And finally, update the value in database.
public void upDateUser(String ID, String money) {
String query = "Select money from TABLE_NAME where ID = " + ID;
SQLiteDatabase db = this.getWriteableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (cursor.moveToFirst()) {
oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, oldMoney + money);
String filter = "UID" + "=" + ID;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
Of course you have to check if cursor returns exactly one row and do some other checks.

take all the values from database and store it in a string array

I have made a vegetable class where i will take all the data from database class and i need to store data in a string array.
Say i have items onion,potato with there price 50,80 in database.
now I need to take those values from database and store in my main class as
String items[] = {"onion","potato"};
String price[] = {"50","80"};
My main class is as follows:
package com.ku.bazzar;
public class VegetableActivity extends Activity {
//String items[];
//String price[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vegetables_info);
I tried something like below:
Vegetablesdatabase info = new Vegetablesdatabase(this);
info.open();
items[] = { info.getvegetable();}
price[]= { info.getprice();}
info.close();
I know this is wrong:
items[] = { info.getvegetable();}
price[]= { info.getprice();}
So anyone can please teach me to make string array of the items and price and also create a method getvegetable() and getprice() in my vegetabledatabase file?
I have made a database class as follows
package com.ku.bazzar;
public class Vegetablesdatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_VEGETABLES = "vegetables";
public static final String KEY_PRICE = "price";
private static final String DATABASE_NAME="ITEM_VEGETABLES";
private static final String DATABASE_TABLE="VEGETABLES";
private static final int DATABASE_VERSION= 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourdatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_VEGETABLES + " TEXT NOT NULL, " +
KEY_PRICE + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Vegetablesdatabase(Context c){
ourContext = c;
}
public Vegetablesdatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourdatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String vegetables, String price) {
ContentValues cv = new ContentValues();
cv.put(KEY_VEGETABLES, vegetables);
cv.put(KEY_PRICE, price);
return ourdatabase.insert(DATABASE_TABLE, null, cv);
}
public String getvegetablename(long l)throws SQLException {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID,KEY_VEGETABLES,KEY_PRICE};
Cursor c= ourdatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l,null, null, null, null);
if(c!= null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getvegetableprice(long l)throws SQLException {
String[] columns = new String[]{ KEY_ROWID,KEY_VEGETABLES,KEY_PRICE};
Cursor c= ourdatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l,null, null, null, null);
if(c!= null){
c.moveToFirst();
String name = c.getString(2);
return name;
}
return null;
}
public void updateentry(long lRow, String vegename, String vegeprice) throws SQLException {
// TODO Auto-generated method stub
ContentValues cvupdate = new ContentValues();
cvupdate.put(KEY_VEGETABLES, vegename);
cvupdate.put(KEY_PRICE, vegeprice);
ourdatabase.update(DATABASE_TABLE, cvupdate, KEY_ROWID + "=" + lRow, null);
}
public String getData() {
String [] columns = new String[]{ KEY_ROWID,KEY_VEGETABLES,KEY_PRICE};
Cursor C =ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = C.getColumnIndex(KEY_ROWID);
int ivegetable = C.getColumnIndex(KEY_VEGETABLES);
int iprice = C.getColumnIndex(KEY_PRICE);
for(C.moveToFirst(); !C.isAfterLast(); C.moveToNext()){
result = result + C.getString(iRow) + " " + C.getString(ivegetable) + " " + C.getString(iprice) + "\n";
}
return result;
}
public void deleteEntry(long lRow1) throws SQLException {
// TODO Auto-generated method stub
ourdatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
}
You can use the answer provides by octopus or by passing the id to it like
for(int i=0;i<strArray.length;i++){
strArray[i] = info.getvegetable(i);
}
Or you can alter the method so that it returns a string array like below
public String[] getvegetablenames()throws SQLException {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID,KEY_VEGETABLES,KEY_PRICE};
Cursor c= ourdatabase.query(DATABASE_TABLE, columns, null,null, null, null, null);
int i=0;
String[] values=new String[c.getCount()];
c.moveToFirst();
do{
values[i] = c.getString(1);
i++;
}while(c.moveToNext());
return values;
}
The above code may have errors but it is enough for you to get started
String array can be initialized directly with values during declaration. but, when you want to initialize the values by invoking a method, this should be followed
String[] strArray = new String[5]; //Ex: 5 is the size of the array
Vegetablesdatabase info = new Vegetablesdatabase(this);
for(int i=0;i<strArray.length;i++){
strArray[i] = info.getvegetable();
}
//strArray is filled with values after the loop
Please note that info.getvegetable() should return a String literal. if you don't want a fixed size collection, go for a list implementation.
You have to go for ArrayList since you don't have the size needed during initialization
public ArrayList<String> getallvegetable() {
String [] columns = new String[]{KEY_VEGETABLES};
Cursor C =ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
ArrayList<String> result = new ArrayList<String>();
int ivegetable = C.getColumnIndex(KEY_VEGETABLES);
int iprice = C.getColumnIndex(KEY_PRICE);
for(C.moveToFirst(); !C.isAfterLast(); C.moveToNext()){
result.add(C.getString(ivegetable));
}
return result;
}
Hope you understand now!

LogCat Syntax error (1)

When trying to add information to my SQLite database which goes to my content provider. I get this error message on my Logcat.
10-21 12:37:48.045: E/SQLiteLog(25929): (1) near "TABLECows": syntax error
I have looked all over and can't seem to find the where the mistake is. When I use the debugger it doesn't give the location of error. Can you help me see what I am missing to correct this error?
My Database.java
package ag.access.cowsdb;
import ag.access.cowsdb.provider.Cows_Provider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class Cowsdatabase extends SQLiteOpenHelper {
private ContentResolver cowcr;
public Cowsdatabase(Context context, String name, CursorFactory factory,
int version) {
super(context,DATABASE_NAME, factory, DATABASE_VERSION);
cowcr = context.getContentResolver();
}
public static final String Key_id = "_id";
public static final String Key_Cow = "Cowid";
public static final String Key_Sire = "Sire";
public static final String Key_Dam = "Dam";
public static final String Key_DOBM = "Month";
public static final String Key_DOBD = "Date";
public static final String Key_DOBY = "Year";
private static final String DATABASE_NAME = "CowsDB";
public static final String DATABASE_TABLE = "Cows";
private static final int DATABASE_VERSION = 1;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String Create_Cows_Table = "CREATE TABLE" +
DATABASE_TABLE + "(" +
Key_id + "INTEGER PRIMARY KEY AUTOINCREMENT," +
Key_Cow + "INTEGER NOT NULL" +
Key_Sire + "TEXT NOT NULL," +
Key_Dam + "TEXT NOT NULL," +
Key_DOBM + "INTEGER NOT NULL," +
Key_DOBD + "INTEGER NOT NULL," +
Key_DOBY + "INTEGER NOT NULL," + ")";
db.execSQL(Create_Cows_Table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
}
public void addcow(cow Cow) {
ContentValues values = new ContentValues();
values.put(Key_Cow, Cow.getCowid());
values.put(Key_Sire, Cow.getSire());
values.put(Key_Dam, Cow.getDam());
values.put(Key_DOBM, Cow.getMonth());
values.put(Key_DOBD, Cow.getDate());
values.put(Key_DOBY, Cow.getYear());
cowcr.insert(Cows_Provider.Content_Uri, values);
}
public cow findcow(int cowid) {
String[] projection = {Key_id, Key_Cow, Key_Sire, Key_Dam, Key_DOBM, Key_DOBD, Key_DOBY};
String selection = "cowid = \"" + cowid + "\"";
Cursor cursor = cowcr.query(Cows_Provider.Content_Uri, projection, selection, null, null);
cow cow = new cow();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
cow.Setid(Integer.parseInt(cursor.getString(0)));
cow.SetCowid(Integer.parseInt(cursor.getString(1)));
cow.setSire(cursor.getString(2));
cow.setDam(cursor.getString(3));
cow.setMonth(Integer.parseInt(cursor.getString(4)));
cow.setDate(Integer.parseInt(cursor.getString(5)));
cow.setYear(Integer.parseInt(cursor.getString(6)));
cursor.close();
} else {
cow = null;
}
return cow;
}
public boolean deleteCow (int cowid) {
boolean result = false;
String selection = "cowid = \"" + cowid + "\"";
int rowsDeleted = cowcr.delete(Cows_Provider.Content_Uri, selection, null);
if (rowsDeleted > 0)
result = true;
return result;
}
}
My Content Provider.java
package ag.access.cowsdb.provider;
import ag.access.cowsdb.Cowsdatabase;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
public class Cows_Provider extends ContentProvider {
private Cowsdatabase cowsdbh;
private static final String Authority =
"ag.access.cowsdb.provider.Cows_Provider";
private static final String Cows = "Cows";
public static final Uri Content_Uri = Uri.parse("content://" + Authority + "/" + Cows);
public static final int COWS = 1;
public static final int COWS_ID = 2;
private static final UriMatcher cURIMatcher =
new UriMatcher(UriMatcher.NO_MATCH);
static {
cURIMatcher.addURI(Authority, Cows, COWS);
cURIMatcher.addURI(Authority, Cows + "/#", COWS_ID);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = cURIMatcher.match(uri);
SQLiteDatabase mysqldb = cowsdbh.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case COWS:
rowsDeleted = mysqldb.delete(Cowsdatabase.DATABASE_TABLE, selection, selectionArgs);
break;
case COWS_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = mysqldb.delete(Cowsdatabase.DATABASE_TABLE, Cowsdatabase.Key_Cow + "=" + id, null);
} else {
rowsDeleted = mysqldb.delete(Cowsdatabase.DATABASE_TABLE, Cowsdatabase.Key_Cow + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknow URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = cURIMatcher.match(uri);
SQLiteDatabase mydb = cowsdbh.getWritableDatabase();
long id = 0;
switch (uriType) {
case COWS:
id = mydb.insert(Cowsdatabase.DATABASE_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknow Uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(Cows + "/" + id);
}
#Override
public boolean onCreate() {
cowsdbh = new Cowsdatabase(getContext(), null, null, 1);
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(Cowsdatabase.DATABASE_TABLE);
int uriType = cURIMatcher.match(uri);
switch (uriType) {
case COWS_ID:
qb.appendWhere(cowsdbh.Key_Cow + "=" + uri.getLastPathSegment());
break;
case COWS:
break;
default:
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = qb.query(cowsdbh.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = cURIMatcher.match(uri);
SQLiteDatabase mysqldb = cowsdbh.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case COWS:
rowsUpdated = mysqldb.update(Cowsdatabase.DATABASE_TABLE, values, selection, selectionArgs);
break;
case COWS_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated =
mysqldb.update(Cowsdatabase.DATABASE_TABLE, values, Cowsdatabase.Key_Cow + "=" + id, null);
} else {
rowsUpdated =
mysqldb.update(Cowsdatabase.DATABASE_TABLE, values, Cowsdatabase.Key_Cow + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI:" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
How and where can i correct this error?
Thanks
On the first line of the onCreate method, add a space, so that it looks like this.
String Create_Cows_Table = "CREATE TABLE " +

Categories