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.
Related
i wanted to append edit text value to in sqlitedb to the new text on top(index 0) and move the previously inserted data down(start from index 1) while inserting rows...Insert the new row on top and display them in a ListView. my code works for appending rows in the bottom .
help me out..
dbhelper.java
public class DBhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "REGISTRATION_DB";
public static final String TABLE_NAME = "REGISTRATION_TABLE";
public static final int VERSION = 1;
public static final String KEY_ID = "_id";
public static final String NAME = "NAME";
public static final String DB = "create table " + TABLE_NAME + " ("
+ KEY_ID + " integer primary key autoincrement, " + NAME
+ " text not null );";
public DBhelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
dataoperation.java
SQLiteDatabase database_ob;
DBhelper openHelper_ob;
Context context;
public Dataoper(Context c) {
// TODO Auto-generated constructor stub
context=c;
}
public Dataoper opnToRead() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getReadableDatabase();
return this;
}
public Dataoper opnToWrite() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public void Close() {
database_ob.close();
}
public long insertData(String fname) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.NAME, fname);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}
public Cursor readdata() {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME };
opnToWrite();
#SuppressWarnings("static-access")
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
null, null, null, null);
return c;
}
public Cursor queryAll(int nameId) {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME};
opnToWrite();
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
openHelper_ob.KEY_ID + "=" + nameId, null, null, null, null);
return c;
}
Mainactivity.java
public class MainActivity extends Activity {
ListView lv;
Dataoper adapter_ob;
DBhelper helper_ob;
SQLiteDatabase db_ob;
Button bt;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list);
bt=(Button)findViewById(R.id.bt);
adapter_ob = new Dataoper(this);
String[] from = { DBhelper.NAME };
int[] to = { R.id.name };
cursor = adapter_ob.readdata();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.listitem_row, cursor, from, to);
lv.setAdapter(cursorAdapter);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
}
You can display the values first which is inserted in last by query
select NAME from REGISTRATION_TABLE orderby _id ASEC
while executing this query,you get cursor values.from cursor value,you need to make arraylist and pass that arraylist to Arrayadapter.
Arraylist<String> al=new ArrayList<String>();
cursor cursor=db.rawquery("select NAME from REGISTRATION_TABLE orderby _id ASEC",null);
if(cursor.getcount()!=0)
{
cursor.movetofirst();
do{
al.add(cursor.getstring(0));
}
while(cursor.movetonext());
}
cursor.close();
Arrayadapter adapter=new Arrayadapter(this,R.layout.simple_list_item_1,al);
lv.setadapter(adapter);
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 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!
I am doing a simple SQlite Apps where I want to save group name in a table and show it on a listview as soon as user click on the add button.
Can any body help me why I am not getting null value from rawQuery result?
public class AddData {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "Grup.db";
public static final int DB_VERSION = 1;
public static final String TABLE = "Grups";
public static final String C_ID = BaseColumns._ID;
public static final String C_CREATED_AT = "easy_ass_created_At";
public static final String C_NAME = "name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public class DbHelper extends SQLiteOpenHelper {
// public static final String TAG = DbHelper.class.getSimpleName();
// public static final String DB_NAME = "Grup.db";
// public static final int DB_VERSION = 1;
// public static final String TABLE = "Grups";
// public static final String C_ID = BaseColumns._ID;
// public static final String C_CREATED_AT = "easy_ass_created_At";
// public static final String C_NAME = "name";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = ("create table " + TABLE + " ( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null" + ");");
db.execSQL(sql);
Log.d(TAG, "OnCreate sql" + sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
Log.d("TAG", "********On Upgrate Drop Table*****");
}
}
public AddData(Context context) {
ourContext = context;
}
public AddData open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
return ourDatabase.insert(TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { C_ID, C_NAME };
Cursor c = ourDatabase.query(TABLE, columns, null, null, null, null,
null);
String result = "";
// int iRow=c.getColumnIndex(C_ID);
int iName = c.getColumnIndex(C_NAME);
// for(c.moveToFirst();!c.isAfterLast();c.moveToLast()){
for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
.moveToNext()) {
result = result + " " + c.getString(iName) + "\n";
c.moveToNext();
}
c.close();
return result;
}
public ArrayList<String> fatchData() {
ArrayList<String> results = new ArrayList<String>();
try {
Cursor c = ourDatabase.rawQuery("SELECT * from Grups;", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("name"));
results.add("Project: " + firstName);
} while (c.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (ourDatabase != null)
ourDatabase.execSQL("DELETE FROM Grups");
ourDatabase.close();
}
return results;
}
}
Try removing c.close() and use startManagingCursor(c) (after creating the cursor) in your getData() method
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.