SQLitedatabase crash after upgrade - java

I added 3 new columns to my Database from version 1 so I changed it to version 2 but now when I use an activity that uses my database my app crashes and shows this in the logcat.
04-02 18:41:09.013: E/AndroidRuntime(19171): FATAL EXCEPTION: main
04-02 18:41:09.013: E/AndroidRuntime(19171):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.fullfrontalgames.numberfighter/com.fullfrontalgames.numberfighter.AccountSettings}:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
04-02 18:41:09.013: E/AndroidRuntime(19171): Caused by:
android.database.sqlite.SQLiteException: near "CREATE": syntax error
(code 1): , while compiling: create table NFDB( ID integer primary key
autoincrement,USERNAME text CREATE UNIQUE INDEX idx_keytype ON
tableName (USERNAME);USERNAME text,PASSWORD text,EMAIL
text,NUMBERINPUT text,SCORE text,FRIENDS text);
I can't see the syntax error anywhere and I have my DBHelper helperclass to drop my old table and make the new table.
here is my code of my DBAdapter and DBHelper classes
package com.fullfrontalgames.numberfighter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBAdapter
{
static final String DATABASE_NAME = "NFDB.db";
static final int DATABASE_VERSION = 2;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"NFDB"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text CREATE UNIQUE INDEX idx_keytype ON tableName (USERNAME);" +
"PASSWORD text,EMAIL text,NUMBERINPUT text,SCORE text,FRIENDS text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper DBHelper;
public DBAdapter(Context _context)
{
context = _context;
DBHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password,String email)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("EMAIL", email);
// Insert the row into your table
db.insert("NFDB", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String userName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("NFDB", where, new String[]{userName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("NFDB", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("NFDB",updatedValues, where, new String[]{userName});
}
public String getData() {
String[] columns = new String[] { "ID", "USERNAME"};
Cursor c = db.query("NFDB", columns, null, null, null, null, null, null);
String result ="";
int iRow = c.getColumnIndex("ID");
int iName = c.getColumnIndex("USERNAME");
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName) + "/n";
}
return result;
}
public String getUsername(String searchName) {
Cursor c = db.query("NFDB",
new String[] { "USERNAME" },
"USERNAME = ?",
new String[] { searchName },
null, null, null);
if (c.moveToNext())
return c.getString(0);
else
return "";
}
public void InsertScore(String Username,String Score)
{
ContentValues ScoreValues = new ContentValues();
ScoreValues.put("USERNAME", Username);
ScoreValues.put("SCORE", Score);
db.insert("NFDB", null, ScoreValues);
}
public String GetGameScore(String Username,String Score)
{
Cursor cursor = db.query("NFDB", null, "USERNAME",new String[]{Username,Score}, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllScore()
{
String[] columns = new String[] {"ID","USERNAME","SCORE"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iUsername = cursor.getColumnIndex("USERNAME");
int iScore = cursor.getColumnIndex("SCORE");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iUsername) + " " + cursor.getString(iScore) + "/n";
}
return result;
}
public void InsertNumber(String Username,String Number)
{
ContentValues NumberValues = new ContentValues();
NumberValues.put("USERNAME", Username);
NumberValues.put("NUMBERINPUT", Number);
db.insert("NFDB", null, NumberValues);
}
public String GetNumber(String Username,String Number)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Number}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllNumbers()
{
String[] columns = new String[] {"ID","USERNAME","NUMBERINPUT"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iNumber = cursor.getColumnIndex("NUMBERINPUT");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iNumber) + "/n";
}
return result;
}
public void InsertFriends (String Username,String Friends)
{
ContentValues FriendValues = new ContentValues();
FriendValues.put("USERNAME", Username);
FriendValues.put("FRIENDS", Friends);
db.insert("NFDB", null, FriendValues);
}
public int DeleteFriends(String Username,String Friends)
{
String where = "USERNAME=?,FRIENDS=?";
int numberOfEntriesDeleted = db.delete("NFDB", where, new String[]{Username,Friends});
return numberOfEntriesDeleted;
}
public String GetFriend(String Username,String Friend)
{
Cursor cursor = db.query("NFDB", null, "USERNAME", new String[]{Username,Friend}, null, null, null, null);
cursor.moveToFirst();
cursor.close();
return Username;
}
public String GetAllFriends()
{
String[] columns = new String[] {"ID","USERNAME","FRIENDS"};
Cursor cursor = db.query("NFDB", columns, null, null, null, null, null, null);
String result="";
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iFriends = cursor.getColumnIndex("FRIENDS");
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(iRow) + " " + cursor.getString(iName) + " " + cursor.getString(iFriends) + "/n";
}
return result;
}
}
package com.fullfrontalgames.numberfighter;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// TODO Auto-generated constructor stub
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DBAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "NFDB");
// Create a new one.
onCreate(_db);
}
}

Your DML statement is incorrect. Index creation cannot be used in CREATE TABLE statement. It must have its own statement.
You have to correct it like this:
DATABASE_CREATE = "create table NFDB("
+ "ID integer primary key autoincrement, "
+ "USERNAME text, PASSWORD text, "
+ "EMAIL text, NUMBERINPUT text, "
+ "SCORE text, FRIENDS text)";
and second statement:
CREATE_INDEX_KEYTYPE = "CREATE UNIQUE INDEX idx_keytype ON tableName(USERNAME)";
And finally, in your SQLiteOpenHelper subclass implementation perform following actions:
_db.execSQL(DBAdapter.DATABASE_CREATE);
_db.execSQL(DBAdapter.CREATE_INDEX_KEYTYPE);

Related

Showing strings from a SQL file in java

I have a SQL file with some data that I want to show in my app, the data will be shown in a list view.
I want to include the SQL file in the apk.
I have three questions:
Is including the SQL file with the apk is the best option or is there a better one?
If putting it in the apk is the best option, where do I put it?
How do I get the strings from the file and show them in the app?
Thanks for the help!
So am really sure what you truly need is an SQLite in android :
Now if that is so, then what you need is to create an adapter class as seen below :
package extension.yourappname.whatever;
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
//public static final String DATABASE_NAME = "my_db";
//public static final String DATABASE_TABLE = "contacts";
//public static final int DATABASE_VERSION = 1;
public static final String START_TBL_CREATION = "create table "+Appiah.DATABASE_TABLE+" (_id integer primary key autoincrement, ";
public static final String [] TABLE_COLUMNS_TO_BE_CREATED = new String []{
KEY_NAME+" text not null, ",
KEY_EMAIL+" text not null"
};
public static final String END_TBL_CREATION = ");";
private static final String DATABASE_CREATE = START_TBL_CREATION
+ TABLE_COLUMNS_TO_BE_CREATED[0]
+ TABLE_COLUMNS_TO_BE_CREATED[1]
+ END_TBL_CREATION;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);//there would be an error initially but just keep going...
}
private static class DatabaseHelper extends SQLiteOpenHelper{//after importing for "SQLiteOpenHelper", Add unimplemented methods
DatabaseHelper(Context context){
super (context, Appiah.DATABASE_NAME, null, Appiah.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
}catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version "+ oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//opens the database
public DBAdapter open() throws SQLiteException{
db = DBHelper.getWritableDatabase();
return this;
}
//closes the database
public void close(){
DBHelper.close();
}
//insert a contact into the database
public long insertContact(String name, String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(Appiah.DATABASE_TABLE, null, initialValues);
}
//deletes a particular contact
public boolean deleteContact(long rowId){
String whereClause = KEY_ROWID + "=" + rowId;
String[] whereArgs = null;
return db.delete(Appiah.DATABASE_TABLE, whereClause, whereArgs) > 0;
}
//retrieves all the contacts
public Cursor getAllContacts(){
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
return db.query(Appiah.DATABASE_TABLE, columns, selection, selectionArgs, groupBy, having, orderBy);
}
//retrieve a particular contact with ID as input
public Cursor getContact_with_ID(long rowId) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_ROWID + "=" + rowId;
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact_with_nameEntered(String name_str) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_NAME + "=" + name_str;//check again and do "%" thing to expand scope and increase chances of a name getting found or populated
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//update a contact
public boolean updateContact(long rowId, String name, String email){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
String table = Appiah.DATABASE_TABLE;
ContentValues values = args;
String whereClause = KEY_ROWID + "=" + rowId;
String []whereArgs = null;
return db.update(table, values, whereClause, whereArgs) > 0;
}
/*
TO USE ANY OF THE ABOVE METHODS :
1. type this before in your "onCreate()" : DBAdapter db = new DBAdapter(this);
2. in the special case of getting all contacts to display : do the ff :
db.open();
Cursor c = db.getAllContacts();
if(c.moveToFirst()){
do{
textView.setText("ID : " + c.getString(0) + "\nName : " + c.getString(1) + "\nEmail Address : " + c.getString(2) );
}while(c.moveToNext());//the "while" added ensures that, the looping process occurs
}
db.close();
*/
}

ANDROID Database cannot find column _id even though it is KEY_ID=_id

Here is my error.
Unable to start activity : no such column: _id (code 1): , while
compiling: SELECT _id, name FROM contacts WHERE _id
Imade sure my column spelled _id instead of id I don't understand why this is happening.
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
private static final String TAG = "MyActivity";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = " CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
void addAddress(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Contact Name
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public boolean deleteAllAddresses() {
SQLiteDatabase db = this.getWritableDatabase();
int doneDelete = 0;
doneDelete = db.delete(TABLE_CONTACTS, null, null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchAddressesbyName(String inputText) throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length() == 0) {
mCursor = db.query(TABLE_CONTACTS, new String[]{KEY_ID,
KEY_NAME,},
null, null, null, null, null);
} else {
mCursor = db.query(true, TABLE_CONTACTS, new String[]{KEY_ID,
KEY_NAME,},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllAddresses() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.query(TABLE_CONTACTS, new String[]{ KEY_ID, KEY_NAME,},KEY_ID , null,null,null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Here is my contact class.
public class Contact {
//private variables
int id;
String name=null;
// getting ID
public int getID(){
return id;
}
// setting id
public void setID(int id){
this.id = id;
}
// getting name
public String getName(){
return name;
}
// setting name
public void setName(String name){
this.name = name;
}
}
Try to upgrade Database_Version from 1 to 2... I think that will help you.

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!

SQLite duplicate entry

I have the following code,but i'm having some trouble with duplicates.How can i modify the code so that it won't allow duplicates in the database ? I'm using it to power an AutoCompleteTextView so the duplicates aren't helping.
Thanks a lot !
package com.giantflyingsaucer;
import android.database.*;
import android.database.sqlite.*;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
public class SQLiteCountryAssistant extends SQLiteOpenHelper
{
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
" (_id integer primary key autoincrement, country_name text not null);)";
private SQLiteDatabase sqliteDBInstance = null;
public SQLiteCountryAssistant(Context context)
{
super(context, DB_NAME, null, DB_VERSION_NUMBER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO: Implement onUpgrade
}
#Override
public void onCreate(SQLiteDatabase sqliteDBInstance)
{
Log.i("onCreate", "Creating the database...");
sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
}
public void openDB() throws SQLException
{
Log.i("openDB", "Checking sqliteDBInstance...");
if(this.sqliteDBInstance == null)
{
Log.i("openDB", "Creating sqliteDBInstance...");
this.sqliteDBInstance = this.getWritableDatabase();
}
}
public void closeDB()
{
if(this.sqliteDBInstance != null)
{
if(this.sqliteDBInstance.isOpen())
this.sqliteDBInstance.close();
}
}
public long insertCountry(String countryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, countryName);
Log.i(this.toString() + " - insertCountry", "Inserting: " + countryName);
return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
}
public boolean removeCountry(String countryName)
{
int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "country_name='" + countryName + "'", null);
if(result > 0)
return true;
else
return false;
}
public long updateCountry(String oldCountryName, String newCountryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, newCountryName);
return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "country_name='" + oldCountryName + "'", null);
}
public String[] getAllCountries()
{
Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, null);
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
}
One option would be to call removeCountry from your insertCountry method before actually doing the insert. Alternatively you could modify your database structure to be country_name text not null unique. SQLite will then throw an exception if you fail the constraint which you'll need to catch and handle appropriately.
Finally, another option would be to attempt a query of the database for the string in question, if it exists, don't insert, if it doesn't then insert it.
You could use a function to see if the data already exists in the database.
public boolean checkIfDataExists(String country) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE_NAME, columns, null, null, null, null, null);
int iCountry = c.getColumnIndex(KEY_COUNTRY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
if (country.equals(c.getString(iCountry))) {
db.close();
return true;
}
}
db.close();
return false;
}
Call this function in an if statement and execute the insert instruction if the condition is not true.
I tried this and it works great,at least so far.
private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
" (_id integer primary key autoincrement, country_name text UNIQUE);)";
Added UNIQUE instead of not null

Delete an Item on Listview but this doesnt deleted from SQLite

I use this method to delete an Item on my SQLite database:
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this to my ListView:
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
The problem is that when i delete an item on my listview the item disappears but when I re-open it the item is still there, because this doesn't remove from the database.
I 'll try to explain this with images :
This means that there is some problem with the deleting from the db. Just replace 2nd line in your deleteItem() with
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item}
Log.d("deletedItem", x);
Here x would be the number of rows deleted. Check the value of x after deleting, it should be greater than 0 if the deletion was successful. If it is not then that means the query is wrong and we would need the database schema for correcting it. From your ListView implementation code, its clear that your nameString itself is wrong. You are adding the whole Item in the arraylist and passing to the adapter. And when you fetch the item in the onItemClick dialog, you are using this code
String nameString = (arg0
.getItemAtPosition(arg2))
.toString();
Here arg0.getItemAtPosition(arg2) would return an Item object. You will have to do something like this.
Item tempItem=(Item)items.get(arg2);
String nameString=tempItem.getName();
where getName() would return the name of the item.
The change that I did:
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
to
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
String nameStringData = nameString.substring(6,
nameString.indexOf("Priority Level:") - 1);
Log.d("itemtodelete", nameStringData);
db.deleteItem(nameStringData);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
If you have a better suggestion please post an answer.
Yes this is the problem.
deletedItem = 0 on logCat so that's my database:
public class DatabaseHolder extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ItemsList";
private static final String TABLE_NAME = "Items";
private static final String ITEMS_COLUMN = "items_name";
private static final String PRIORITY_COLUMN = "Priority";
private static final String ID_COLUMN = "Items";
private static int DATABASE_VERSION = 1;
private static String QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEMS_COLUMN
+ " TEXT NOT NULL, " + PRIORITY_COLUMN + " TEXT NOT NULL);";
public DatabaseHolder(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
// Sharer!
public void addItem(String item_name, String priority) {
if (!duplicate(item_name)) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEMS_COLUMN, item_name);
values.put(PRIORITY_COLUMN, priority);
db.beginTransaction();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
public boolean duplicate(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, ITEMS_COLUMN + " =?",
new String[] { name }, null, null, null);
int temp = c.getCount();
c.close();
db.close();
if (temp > 0)
return true;
else
return false;
}
public ArrayList<Item> getAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Item> item = new ArrayList<Item>();
db.beginTransaction();
Cursor cursor = db.query(TABLE_NAME, new String[] { this.ITEMS_COLUMN,
this.PRIORITY_COLUMN }, null, null, null, null, PRIORITY_COLUMN
+ " DESC");
while (cursor.moveToNext()) {
Item itemTemp = new Item(cursor.getString(cursor
.getColumnIndexOrThrow(ITEMS_COLUMN)), new Level(
Integer.parseInt(cursor.getString(cursor
.getColumnIndexOrThrow(PRIORITY_COLUMN)))));
item.add(itemTemp);
}
cursor.close();
db.endTransaction();
db.close();
return item;
}
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
Log.d("deletedItem", String.valueOf(x) );
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}

Categories