A database has already been created within code, very similar to the code i am about to paste. I kept the database name the same and wanted to create a new table.
Could anyone offer some assistance, thank you.
The error i am getting is:
04-28 00:03:10.182: I/Database(310): sqlite returned: error code = 1, msg =
no such table: stats
04-28 00:03:10.202: E/Database(310): Error inserting username= height=
weight= protein= age= fats= calories= carbs=
04-28 00:03:10.202: E/Database(310):
android.database.sqlite.SQLiteException: no such table: stats: , while
compiling: INSERT INTO stats(username, height, weight, protein, age,
fats, calories, carbs) VALUES(?, ?, ?, ?, ?, ?, ?, ?);
AddStats.Java
package com.gofitness.www;
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 AddStats {
public static final String KEY_ROWID = "userid";
public static final String KEY_NAME = "username";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_HEIGHT = "height";
public static final String KEY_AGE = "age";
public static final String KEY_CALORIES = "calories";
public static final String KEY_PROTEIN = "protein";
public static final String KEY_CARBS = "carbs";
public static final String KEY_FATS = "fats";
private static final String DATABASE_NAME = "gofitness";
private static final String DATABASE_TABLE = "stats";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
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 dbstats) {
// TODO Auto-generated method stub
dbstats.execSQL(
"CREATE TABLE " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " INT NOT NULL, " +
KEY_CALORIES + " INT NOT NULL, " +
KEY_WEIGHT + " INT NOT NULL, " +
KEY_HEIGHT + " INT NOT NULL, " +
KEY_PROTEIN + " INT NOT NULL, " +
KEY_FATS + " INT NOT NULL, " +
KEY_CARBS + " INT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase dbstats, int oldVersion, int n
newVersion) {
// TODO Auto-generated method stub
dbstats.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(dbstats);
}
}
public AddStats(Context c)
{
ourContext = c;
}
public AddStats open(){
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String usernamevar, String agevar,String weightvar,String
heightvar,String caloriesvar,
String proteinvar, String carbsvar, String fatvar) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME,usernamevar);
cv.put(KEY_AGE,agevar);
cv.put(KEY_WEIGHT,weightvar);
cv.put(KEY_HEIGHT,heightvar);
cv.put(KEY_CALORIES,caloriesvar);
cv.put(KEY_PROTEIN,proteinvar);
cv.put(KEY_CARBS,carbsvar);
cv.put(KEY_FATS,fatvar);
return ourDatabase.insert(DATABASE_TABLE,null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME,
KEY_AGE,KEY_WEIGHT,KEY_HEIGHT, KEY_CALORIES,KEY_PROTEIN,KEY_CARBS,KEY_FATS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iUser = c.getColumnIndex(KEY_NAME);
int iAge = c.getColumnIndex(KEY_AGE);
int iWeight = c.getColumnIndex(KEY_WEIGHT);
int iHeight = c.getColumnIndex(KEY_HEIGHT);
int iCalories = c.getColumnIndex(KEY_CALORIES);
int iProtein = c.getColumnIndex(KEY_PROTEIN);
int iCarb = c.getColumnIndex(KEY_CARBS);
int iFat = c.getColumnIndex(KEY_FATS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iUser) + " " +
c.getString(iAge) + c.getString(iWeight)
+ c.getString(iHeight) + c.getString(iCalories)+
c.getString(iProtein) + c.getString(iCarb) + c.getString(iFat) +"\n";
}
return result;
}
}
AddStatsForm.Java
package com.gofitness.www;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddStatsForm extends Activity implements OnClickListener {
EditText username, age, weight,height, calories, protein, carbs, fat;
TextView success;
Button submit;
#Override
protected void onCreate(Bundle viewInfo) {
// TODO Auto-generated method stub
super.onCreate(viewInfo);
setContentView(R.layout.stats);
submit = (Button) findViewById(R.id.bEnter);
username = (EditText) findViewById(R.id.etUsername);
age = (EditText) findViewById(R.id.etAge);
weight = (EditText) findViewById(R.id.etWeight);
height = (EditText) findViewById(R.id.etHeight);
calories = (EditText) findViewById(R.id.etCalories);
protein = (EditText) findViewById(R.id.etProtein);
carbs = (EditText) findViewById(R.id.etCarbs);
fat = (EditText) findViewById(R.id.etFat);
success = (TextView) findViewById(R.id.tvSuccess);
submit.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String usernamevar = username.getText().toString();
String agevar = age.getText().toString();
String weightvar = weight.getText().toString();
String heightvar = height.getText().toString();
String caloriesvar = calories.getText().toString();
String proteinvar = protein.getText().toString();
String carbsvar = carbs.getText().toString();
String fatvar = fat.getText().toString();
AddStats entry = new AddStats(AddStatsForm.this);
entry.open();
entry.createEntry(usernamevar ,agevar, weightvar, h
heightvar, caloriesvar, proteinvar, carbsvar, fatvar);
entry.close();
}}
Increase your DATABASE_VERSION variable to at least 2. When your app is updated and runs again, when it tries to open the database, the system will recognize that the existing database has a lower version number than the version number you've specified. It will call onUpgrade() and give you the old version and the new version. Use that information to make the appropriate changes to your database.
Currently your onUpgrade method just deletes the exiting table and calls onCreate again, which will work, but it won't preserve any existing data. You might consider something like this instead:
#Override
public void onUpgrade(SQLiteDatabase dbstats, int oldVersion, int newVersion) {
if (oldVersion == 1) {
db.execSql(/* create second table */);
}
}
Related
At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..
Ok so here is the whole code
This is MainActivity.java
package com.gobtron.database_test;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
populateListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_ViewData (View v){
openDB();
populateListView();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
// DatabaseUtils.dumpCursor(cursor);
String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_NOM};
int[] toViewIDs = new int[] {R.id.textView2, R.id.textView3};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, cursor.getCount());
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
}
And this is the DPAdapter class code:
package com.gobtron.database_test;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_MORPH = "'morph'";
public static final String KEY_LONGFRONDE = "'long_fronde'";
public static final String KEY_FORMELIMBE = "'forme_limbe'";
public static final String KEY_DISPOSFRONDE = "'dispos_fronde'";
public static final String KEY_DESC = "'description'";
public static final String KEY_DESCHOIX = "'desc_choix'";
public static final String KEY_DESCHOIX2 = "'desc_choix2'";
public static final String KEY_NOM = "'nom'";
public static final String[] ALL_KEYS ={KEY_ROWID, KEY_MORPH, KEY_LONGFRONDE, KEY_FORMELIMBE, KEY_DISPOSFRONDE, KEY_DESC, KEY_DESCHOIX, KEY_DESCHOIX2, KEY_NOM};
public static final String[] ALL_KEYS2 = {"_id", "'long_fronde'"};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_MORPH = 1;
public static final int COL_LONGFRONDE = 2;
public static final int COL_FORMELIMBE = 3;
public static final int COL_DISPOSFRONDE = 4;
public static final int COL_DESC = 5;
public static final int COL_DESCHOIX = 6;
public static final int COL_DESCHOIX2 = 7;
public static final int COL_NOM = 8;
// DataBase info:
public static final String DATABASE_NAME = "fougeres_db";
public static final String DATABASE_TABLE = "mono_dimo";
public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String task, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NOM, task);
initialValues.put(KEY_MORPH, date);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null, null);
DatabaseUtils.dumpCursor(c);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NOM, task);
newValues.put(KEY_MORPH, date);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I don't get why my cursor is empty... I think it opens the database correctly, and the table too.
Well... I'm new to java so it is probably something stupid i'm missing.
You are trying to insert a value with key KEY_MORTH, however there is no field with this Key in your table
this:
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY , "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT"
+ ");";
needs to be
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT, "
+ KEY_MORTH + " TEXT "
+ ");";
You will need to update your db version or clear your data for this to take effect
Ok, turns out that my database was simply put in the wrong place. I needed to open the Android Device Monitor, then go the File Explorer, then put my existing database to /data/data/my package name/databases/
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.
I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 + " TEXT NOT NULL, " + KEY_CREDITS + " 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 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;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£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.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
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);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection
I am attempting to list all the tables I have in my database in a list view by creating a string array of the table names then passing them to a listView, I have a button which calls the activity which creates the listview. the activity calls getDbNames from my database class. I get this error in LogCat in eclipse:
Tag - CursorWindow
Text - Bad request for field slot 1,-1. numRows = 3, numColumns = 1
I'll include my whole database class to see if you can help.
package the.paddox.pool;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "newplayersname";
public static final String KEY_PERCENTAGE = "percentage";
private static final String DATABASE_NAME = "paddoxa";
private static final String DATABASE_TABLE = "players";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public 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 AUTOINCREMENT, " +
KEY_NAME + " 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 Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String[] getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_NAME};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result ="";
String[] mString = {""};
ArrayList<String> playersData = new ArrayList<String>();
int iName = c.getColumnIndex(KEY_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = c.getString(iName);
playersData.add(result);
}
mString = (String[]) playersData.toArray(new String[playersData.size()]);
return mString;
}
public String[] getDBNames() {
String[] result = null;
Cursor c = ourDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
c.moveToFirst();
result = new String[c.getCount()];
int i = 0;
while (c.moveToNext()) {
result[i] = c.getString(c.getColumnIndex(DATABASE_TABLE));
i++;
}
return result;
}
}
Any help would be greatly appreciated.
I think,you are getting this error because where you try to get iName,you haven't call c.moveToFirst(); before that statement!
Instead you can use it like:
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = c.getString(c.getColumnIndex(KEY_NAME));
playersData.add(result);
}
please check your Query "SELECT name FROM sqlite_master WHERE type='table'" in getDBNames() as it list rows for column for name
your c.getColumnIndex(DATABASE_TABLE) // DATABASE_TABLE = "players" in your code. will actually not work and return as -1.
For details check here.
Hope this will help you to work further.