SQLite duplicate entry - java

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

Related

android sqlite cursor object null while fetching a record

I've following dbadapter class, whenever i try to delete a record from the database or fetch any particular contact cursor objet is returned null everytime. anyone know why ?
my code snippets are
dbadapter.java:
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 KEY_STUID ="stuid";
public static final String KEY_PASS ="password";
public static final String KEY_SEM ="sem";
public static final String KEY_YEAR ="year";
public static final String KEY_TYPE="type";
public static final String KEY_NOTIFY="notify";
private static final String TAG ="DBAdapter";
private static final String DATABASE_NAME ="MyDB";
private static final String DATABASE_TABLE ="contacts";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE ="create table contacts (_id integer primary key autoincrement,"+"name text not null, stuid text not null, password text not null, sem text not null, year text not null, type text not null, notify text not null);";
private Context context = null;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context=ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 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 SQLException
{
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 stuid , String password , String sem , String year , String type , String notify)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_STUID, stuid);
initialValues.put(KEY_PASS, password);
initialValues.put(KEY_SEM, sem);
initialValues.put(KEY_YEAR, year);
initialValues.put(KEY_TYPE, type);
initialValues.put(KEY_NOTIFY, notify);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID +"="+ rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_STUID, KEY_PASS, KEY_SEM, KEY_YEAR, KEY_TYPE, KEY_NOTIFY}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_STUID, KEY_PASS, KEY_SEM, KEY_YEAR, KEY_TYPE, KEY_NOTIFY}, KEY_ROWID +"=" + rowId, null,
null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
return mCursor;
}
else {
mCursor.close();
}
return null;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String stuid , String password , String sem , String year , String type , String notify)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_STUID, stuid);
args.put(KEY_PASS, password);
args.put(KEY_SEM, sem);
args.put(KEY_YEAR, year);
args.put(KEY_TYPE, type);
args.put(KEY_NOTIFY, notify);
return db.update(DATABASE_TABLE, args, KEY_ROWID +"="+ rowId, null) > 0;
}
}
I am calling the method from listview in mainactivity.java as
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,"You clicked at "+position,Toast.LENGTH_SHORT).show();
try {
Cursor cursor1;
cursor1 = dbhelper.getContact(position + 1);
Toast.makeText(MainActivity.this, "id=" + cursor1.getString(2) + " pass=" + cursor1.getString(3) + " session=" + cursor1.getString(4) + " year=" + cursor1.getString(5) + " type=" + cursor1.getString(6), Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
which generates null pointer exception. please help.
Note : getallcontacts() and insertcontact() methods work fine.
Try this in your getContact Method;
if (mCursor != null && mCursor.moveToFirst())
{
String val1 = mCursor.getString("ColumnName1");
String val2 = mCursor.getString("ColumnName2");
// Check if Expected Record is returned
Toast.make(Context, val1+val2, Toast.LONG).show();
return mCursor;
}
else
{
return mCursor =null;
}
// Close Cursor after Retrieving Values from it.
if (!mCursor.close())
{
mCursor.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.

Error parsing XML - not well formed (invalid token)

I have already checked the other XML files for errors, however this is the file that the error message is saying the error is in. There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
package com.example.drive.drivercorder;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_DRIVETIME = "Drive Time";
public static final String KEY_NIGHTORDAY = "Time of Day";
public static final int COL_DRIVETIME = 1;
public static final int COL_NIGHTORDAY = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_DRIVETIME, KEY_NIGHTORDAY, };
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DRIVETIME + " integer not null, "
+ KEY_NIGHTORDAY + " text not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(int drivetime, String nightorday) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DRIVETIME, Drive Time);
initialValues.put(KEY_NIGHTORDAY, Time of Day);
return db.insert(DATABASE_TABLE, null, initialValues);
}
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();
}
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
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;
}
public boolean updateRow(long rowId, String drivetime, String nightorday) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_DRIVETIME, Drive Time);
newValues.put(KEY_NIGHTORDAY, Time of Day);
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!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
I think you are changing the .class file in debug/DDMS mode or something like that. Please check and make sure to edit your .java file instead.
Posting your relevant logcat messages and also the XML file in question might help understand the problem.

SQLiteDatabase onCreate() and onUpgrade() not being called

I'm developing an app that (so far) pulls data from an API, inserts it to a local SQLite database & displays it on screen.
In order to make my life simpler, I wrote a master database adapter (MyDBAdapter) as well as adapters for each individual table, according to the top anser for this question.
While developing the app, I'm also teaching myself unit testing in JUnit (not sure if this is relevant, but I figured I'd throw it in there).
When trying to refresh the database I somehow dropped all the tables and now I can't get them back. When I increment the DB_VERSION value, onUpgrade() doesn't get called, and the app errors out because it's trying to access nonexistent tables.
What circumstances would cause onUpgrade() to not get called? I'm at my wits' end trying to figure this out.
MyDbAdapter:
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDbAdapter {
public static final String TAG = "MyDbAdapter";
protected static final String DB_NAME = "mydb.db";
protected static final int DB_VERSION = 21;
private final Context context;
private DbHelper helper;
private SQLiteDatabase db;
private static final String CREATE_TABLE_CRUISE_LINES = "create table " + CruiseLineAdapter.TABLE + " (" + CruiseLineAdapter.C_ID + " integer primary key autoincrement, "
+ CruiseLineAdapter.C_NAME + " TEXT);";
private static final String CREATE_TABLE_SHIPS = "create table " + ShipAdapter.TABLE + " (" + ShipAdapter.C_ID + " integer primary key autoincrement, "
+ ShipAdapter.C_NAME + " TEXT, "
+ ShipAdapter.C_CRUISE_LINE + " integer);";
private static final String CREATE_TABLE_TABLE_UPDATES = "create table " + UpdateTimestampAdapter.TABLE + " (" + UpdateTimestampAdapter.C_ID + " integer primary key autoincrement, "
+ UpdateTimestampAdapter.C_TABLE_NAME + " TEXT, "
+ UpdateTimestampAdapter.C_LAST_UPDATE + " TEXT);";
private static final String DROP_TABLE = "drop table if exists %s";
private static final String DROP_TABLE_CRUISE_LINES = String.format(DROP_TABLE, CruiseLineAdapter.TABLE);
private static final String DROP_TABLE_SHIPS = String.format(DROP_TABLE, ShipAdapter.TABLE);
private static final String DROP_TABLE_TABLE_UPDATES = String.format(DROP_TABLE, UpdateTimestampAdapter.TABLE);
public MyDbAdapter (Context context) {
this.context = context;
helper = new DbHelper(this.context);
}
private static class DbHelper extends SQLiteOpenHelper {
DbHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
Log.i(TAG, "initialized");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Database created: version " + DB_VERSION);
db.execSQL(CREATE_TABLE_CRUISE_LINES);
db.execSQL(CREATE_TABLE_SHIPS);
db.execSQL(CREATE_TABLE_TABLE_UPDATES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "Database upgraded to " + DB_VERSION);
db.execSQL(DROP_TABLE_CRUISE_LINES);
db.execSQL(DROP_TABLE_SHIPS);
db.execSQL(DROP_TABLE_TABLE_UPDATES);
this.onCreate(db);
}
}
public MyDbAdapter open() throws SQLException {
db = helper.getWritableDatabase();
return this;
}
public void close() {
helper.close();
}
}
ShipAdapter:
import java.util.ArrayList;
import java.util.List;
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;
import android.provider.BaseColumns;
public class ShipAdapter {
public static final String TAG = "ShipAdapter";
public static final String TABLE = "ships";
public static final String C_ID = BaseColumns._ID;
public static final String C_NAME = "name";
public static final String C_CRUISE_LINE = "cruise_line";
private DbHelper dbHelper;
private SQLiteDatabase db;
private final Context context;
private static class DbHelper extends SQLiteOpenHelper {
DbHelper (Context context) {
super(context, MyDbAdapter.DB_NAME, null, MyDbAdapter.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public ShipAdapter(Context context) {
this.context = context;
}
public ShipAdapter open() throws SQLException {
dbHelper = new DbHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createShip(String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insert(TABLE, null, initialValues);
}
public long createShip(long id, String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_ID, id);
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insert(TABLE, null, initialValues);
}
public long createShip(ShipModel ship) {
return createShip(ship.getName(), ship.getCruiseLineId());
}
public long insertOrIgnoreShip(long id, String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_ID, id);
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insertWithOnConflict(TABLE, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertOrIgnoreShip(ShipModel ship) {
return insertOrIgnoreShip(ship.getId(), ship.getName(), ship.getCruiseLineId());
}
public List<ShipModel> getAllShips() {
List<ShipModel> ships = new ArrayList<ShipModel>();
Cursor cursor = getAllShipsCursor();
if (cursor.getCount() > 0) {
while(!cursor.isAfterLast()) {
ships.add(cursorToShip(cursor));
cursor.moveToNext();
}
}
return ships;
}
public Cursor getAllShipsCursor() {
Cursor cursor = db.query(TABLE, null, null, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public ShipModel getShip(long id) {
Cursor cursor = getShipCursor(id);
if (cursor.getCount() > 0) {
return cursorToShip(cursor);
}
return null;
}
public Cursor getShipCursor(long id) {
Cursor cursor = db.query(TABLE, null, C_ID + " = ?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public ShipModel getShip(String name) {
Cursor cursor = getShipCursor(name);
if (cursor.getCount() > 0) {
return cursorToShip(cursor);
}
return null;
}
public Cursor getShipCursor(String name) {
Cursor cursor = db.query(TABLE, null, C_NAME + " = ?", new String[] { name }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public List<ShipModel> getShipsByCruiseLine(long cruise_line_id) {
List<ShipModel> ships = new ArrayList<ShipModel>();
Cursor cursor = getShipsCursorByCruiseLine(cruise_line_id);
if (cursor.getCount() > 0) {
while (!cursor.isAfterLast()) {
ships.add(cursorToShip(cursor));
cursor.moveToNext();
}
}
return ships;
}
public Cursor getShipsCursorByCruiseLine(long cruise_line_id) {
Cursor cursor = db.query(TABLE, null, C_CRUISE_LINE + " = ?", new String[] { String.valueOf(cruise_line_id) }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public boolean updateShip(long id, String name, long cruise_line_id) {
ContentValues args = new ContentValues();
args.put(C_NAME, name);
args.put(C_CRUISE_LINE, cruise_line_id);
return db.update(TABLE, args, C_ID + " = ?", new String[] { String.valueOf(id) }) > 0;
}
public boolean updateShip(ShipModel ship) {
return updateShip(ship.getId(), ship.getName(), ship.getCruiseLineId());
}
public boolean deleteShip(long id) {
return db.delete(TABLE, C_ID + " = ?", new String[] { String.valueOf(id) }) > 0;
}
public boolean deleteShip(String name) {
return db.delete(TABLE, C_NAME + " = ?", new String[] { name }) > 0;
}
public boolean deleteShip(ShipModel ship) {
return deleteShip(ship.getName());
}
public boolean deleteAll() {
return db.delete(TABLE, null, null) > 0;
}
private ShipModel cursorToShip(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(C_ID));
String name = cursor.getString(cursor.getColumnIndex(C_NAME));
long cruise_line_id = cursor.getLong(cursor.getColumnIndex(C_CRUISE_LINE));
return new ShipModel(id, name, cruise_line_id);
}
}
Communicator:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NoHttpResponseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Created by mcampo on 5/30/13.
*/
public class Communicator {
private static final String TAG = "Communicator";
private static final int CONNECTION_TIMEOUT = 10000;
protected String base_url = "http://[myapi]/mobileapi/";
protected Context context;
protected CruiseLineAdapter cruise_line_adapter;
protected ShipAdapter ship_adapter;
protected UpdateTimestampAdapter table_update_adapter;
protected String update_timestamps_json;
public Communicator() {
}
public Communicator (Context context) {
this.context = context;
this.cruise_line_adapter = new CruiseLineAdapter(this.context);
this.ship_adapter = new ShipAdapter(this.context);
this.table_update_adapter = new UpdateTimestampAdapter(this.context);
}
// begin defining getters / setters
/**
*
* #param context
*/
public void setContext(Context context) {
this.context = context;
this.cruise_line_adapter = new CruiseLineAdapter(this.context);
this.ship_adapter = new ShipAdapter(this.context);
this.table_update_adapter = new UpdateTimestampAdapter(this.context);
}
public Context getContext() {
return this.context;
}
// end getters / setters
private boolean isNetworkConnected() {
if (context == null) {
return false;
}
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
private String makeApiCall(String api_extension) throws IOException {
if (!isNetworkConnected()) {
throw new IOException("Your device is not connected to the internet. Please enable your network connection and restart CabinGuru.");
}
Log.d(TAG, "Making HTTP request to " + this.base_url + api_extension);
HttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
HttpResponse response = httpClient.execute(new HttpGet(this.base_url + api_extension));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
Log.i(TAG, "HTTP Response: " + out.toString());
return out.toString();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
private boolean tableIsUpToDate(String table) throws IOException {
try {
String api_timestamp = getApiUpdateTimestamp(table);
String device_timestamp = getDeviceUpdateTimestamp(table);
if (device_timestamp == null || device_timestamp.equals("")) {
throw new NullPointerException("device_timestamp is null");
}
Log.i(TAG, "API Timestamp: " + api_timestamp);
Log.i(TAG, "Device Timestamp: " + device_timestamp);
// compare device_timestamp to api_timestamp. If device_timestamp comes after api_timestamp, table is up-to-date.
DateTime api_datetime = this.strToDateTime(api_timestamp);
DateTime device_datetime = this.strToDateTime(device_timestamp);
return device_datetime.isAfter(api_datetime);
} catch (NullPointerException e) {
e.printStackTrace();
Log.e(TAG, "NullPointerException encountered in tableIsUpToDate(" + table + "): " + e.getMessage() + " " + e.getCause());
return false;
}
}
private String getDeviceUpdateTimestamp(String table) {
String return_string = "";
table_update_adapter.open();
UpdateTimestampModel timestamp = this.table_update_adapter.getUpdateTimestamp(table);
table_update_adapter.close();
try {
return_string = timestamp.getLastUpdate();
return return_string;
} catch (NullPointerException e) {
Log.e(TAG, "NullPointerException encountered in getDeviceUpdateTimestamp(" + table + "): " + e.getMessage());
return "";
}
}
private boolean updateLastUpdateTimestamp(String table) {
// set up current timestamp
DateTime timestamp = new DateTime(System.currentTimeMillis());
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
String now = formatter.print(timestamp);
// fetch ID of row to update
table_update_adapter.open();
table_update_adapter.updateOrCreateTimestamp(table, now);
table_update_adapter.close();
return true;
}
private void getApiUpdateTimestamps() throws IOException {
if (this.update_timestamps_json == null || this.update_timestamps_json.equals(""))
try {
this.update_timestamps_json = this.makeApiCall("get_update_timestamps");
} catch (NoHttpResponseException e) {
Log.e(TAG, "App was unable to connect to the servers.");
}
}
private String getApiUpdateTimestamp(String table) throws IOException {
this.getApiUpdateTimestamps();
try {
if (this.update_timestamps_json == null) {
throw new Exception("Could not fetch update timestamps. Check and make sure you are able to connect to " + this.base_url + ".");
}
JSONObject timestamps = new JSONObject(this.update_timestamps_json);
return timestamps.getString(table);
} catch (JSONException e) {
Log.e(TAG, "An error occurred when extracting update timestamps from the api: " + e.getMessage() + " | " + e.getCause());
return null;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return null;
}
}
public boolean updateCruiseLines() throws IOException {
// if the cruise lines from the API have been updated since the last update on the device, update the device.
if (!this.tableIsUpToDate(CruiseLineAdapter.TABLE)) {
Log.i(TAG, "Attempting API call for Cruise Lines.");
try {
String cruise_line_json = this.makeApiCall("cruise_lines");
JSONArray cruise_lines = new JSONArray(cruise_line_json);
// loop through cruise_lines, add to database
int array_size = cruise_lines.length();
cruise_line_adapter.open();
for (int i = 0; i < array_size; i++) {
JSONObject cruise_line = cruise_lines.getJSONObject(i);
int cruise_line_id = cruise_line.getInt("CruiseLineID");
String cruise_line_name = cruise_line.getString("Name");
// insert record into database.
this.cruise_line_adapter.insertOrIgnoreCruiseLine(cruise_line_id, cruise_line_name);
}
cruise_line_adapter.close();
this.updateLastUpdateTimestamp(CruiseLineAdapter.TABLE);
} catch (JSONException e) {
Log.e(TAG, "JSONException encountered in updateCruiseLines(): " + e.getMessage());
e.printStackTrace();
return false;
}
} else {
Log.i(TAG, "Cruise Line records exist. No API call necessary.");
}
return true;
}
public boolean updateShips() throws IOException {
// if the ships from the API have been updated since the last update on the device, update the device
if (!this.tableIsUpToDate(ShipAdapter.TABLE)) {
Log.i(TAG, "Attempting API call for Ships.");
try {
String ships_json = this.makeApiCall("ships");
JSONArray ships = new JSONArray(ships_json);
// loop through ships, add to database
int array_size = ships.length();
ship_adapter.open();
for (int i = 0; i < array_size; i++) {
JSONObject ship = ships.getJSONObject(i);
int id = ship.getInt("ShipID");
String name = ship.getString("ShipName");
int cruise_line_id = ship.getInt("CruiseLineID");
this.ship_adapter.insertOrIgnoreShip(id, name, cruise_line_id);
}
ship_adapter.close();
this.updateLastUpdateTimestamp(ShipAdapter.TABLE);
} catch (JSONException e) {
Log.e(TAG, "JSONException encountered in updateShips():" + e.getMessage());
e.printStackTrace();
return false;
}
} else {
Log.i(TAG, "Ship records exist. No API call necessary.");
}
return true;
}
private DateTime strToDateTime(String timestamp) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
return formatter.parseDateTime(timestamp);
}
}
Android would not be able to figure out that it needs to run MyDbAdapter on its own.
Create a class that extends Application.
public class MyApplication extends Application {
private static MyDbAdapter dbAdapter;
#Override
public void onCreate() {
super.onCreate();
dbAdapter = new MyDbAdapter(getApplicationContext());
}
}
On your AndroidManifest.xml, you need to set the attribute in the application element like this:
<application
android:name=".MyApplication"
...
/application>
After stepping away from the problem for a few hours I came up with this solution:
Instead of making the *Adapter classes independent of one another, I modified the code to make them children of MyDBAdapter. This way, when open() is called, it calls the open() method of MyDBAdapter, checking the DB version & upgrading when appropriate.
MyDbAdapter:
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDbAdapter {
public static final String TAG = "MyDbAdapter";
protected static final String DB_NAME = "mydb.db";
protected static final int DB_VERSION = 21;
private final Context context;
private DbHelper helper;
private SQLiteDatabase db;
private static final String CREATE_TABLE_CRUISE_LINES = "create table " + CruiseLineAdapter.TABLE + " (" + CruiseLineAdapter.C_ID + " integer primary key autoincrement, "
+ CruiseLineAdapter.C_NAME + " TEXT);";
private static final String CREATE_TABLE_SHIPS = "create table " + ShipAdapter.TABLE + " (" + ShipAdapter.C_ID + " integer primary key autoincrement, "
+ ShipAdapter.C_NAME + " TEXT, "
+ ShipAdapter.C_CRUISE_LINE + " integer);";
private static final String CREATE_TABLE_TABLE_UPDATES = "create table " + UpdateTimestampAdapter.TABLE + " (" + UpdateTimestampAdapter.C_ID + " integer primary key autoincrement, "
+ UpdateTimestampAdapter.C_TABLE_NAME + " TEXT, "
+ UpdateTimestampAdapter.C_LAST_UPDATE + " TEXT);";
private static final String DROP_TABLE = "drop table if exists %s";
private static final String DROP_TABLE_CRUISE_LINES = String.format(DROP_TABLE, CruiseLineAdapter.TABLE);
private static final String DROP_TABLE_SHIPS = String.format(DROP_TABLE, ShipAdapter.TABLE);
private static final String DROP_TABLE_TABLE_UPDATES = String.format(DROP_TABLE, UpdateTimestampAdapter.TABLE);
public MyDbAdapter (Context context) {
this.context = context;
helper = new DbHelper(this.context);
}
private static class DbHelper extends SQLiteOpenHelper {
DbHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
Log.i(TAG, "initialized");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Database created: version " + DB_VERSION);
db.execSQL(CREATE_TABLE_CRUISE_LINES);
db.execSQL(CREATE_TABLE_SHIPS);
db.execSQL(CREATE_TABLE_TABLE_UPDATES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "Database upgraded to " + DB_VERSION);
db.execSQL(DROP_TABLE_CRUISE_LINES);
db.execSQL(DROP_TABLE_SHIPS);
db.execSQL(DROP_TABLE_TABLE_UPDATES);
this.onCreate(db);
}
}
public MyDbAdapter open() throws SQLException {
db = helper.getWritableDatabase();
return this;
}
public void close() {
helper.close();
}
}
ShipAdapter:
import java.util.ArrayList;
import java.util.List;
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;
import android.provider.BaseColumns;
public class ShipAdapter extends MyDbAdapter {
public static final String TAG = "ShipAdapter";
public static final String TABLE = "ships";
public static final String C_ID = BaseColumns._ID;
public static final String C_NAME = "name";
public static final String C_CRUISE_LINE = "cruise_line";
public ShipAdapter(Context context) {
this.context = context;
}
public long createShip(String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insert(TABLE, null, initialValues);
}
public long createShip(long id, String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_ID, id);
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insert(TABLE, null, initialValues);
}
public long createShip(ShipModel ship) {
return createShip(ship.getName(), ship.getCruiseLineId());
}
public long insertOrIgnoreShip(long id, String name, long cruise_line_id) {
ContentValues initialValues = new ContentValues();
initialValues.put(C_ID, id);
initialValues.put(C_NAME, name);
initialValues.put(C_CRUISE_LINE, cruise_line_id);
return db.insertWithOnConflict(TABLE, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertOrIgnoreShip(ShipModel ship) {
return insertOrIgnoreShip(ship.getId(), ship.getName(), ship.getCruiseLineId());
}
public List<ShipModel> getAllShips() {
List<ShipModel> ships = new ArrayList<ShipModel>();
Cursor cursor = getAllShipsCursor();
if (cursor.getCount() > 0) {
while(!cursor.isAfterLast()) {
ships.add(cursorToShip(cursor));
cursor.moveToNext();
}
}
return ships;
}
public Cursor getAllShipsCursor() {
Cursor cursor = db.query(TABLE, null, null, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public ShipModel getShip(long id) {
Cursor cursor = getShipCursor(id);
if (cursor.getCount() > 0) {
return cursorToShip(cursor);
}
return null;
}
public Cursor getShipCursor(long id) {
Cursor cursor = db.query(TABLE, null, C_ID + " = ?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public ShipModel getShip(String name) {
Cursor cursor = getShipCursor(name);
if (cursor.getCount() > 0) {
return cursorToShip(cursor);
}
return null;
}
public Cursor getShipCursor(String name) {
Cursor cursor = db.query(TABLE, null, C_NAME + " = ?", new String[] { name }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public List<ShipModel> getShipsByCruiseLine(long cruise_line_id) {
List<ShipModel> ships = new ArrayList<ShipModel>();
Cursor cursor = getShipsCursorByCruiseLine(cruise_line_id);
if (cursor.getCount() > 0) {
while (!cursor.isAfterLast()) {
ships.add(cursorToShip(cursor));
cursor.moveToNext();
}
}
return ships;
}
public Cursor getShipsCursorByCruiseLine(long cruise_line_id) {
Cursor cursor = db.query(TABLE, null, C_CRUISE_LINE + " = ?", new String[] { String.valueOf(cruise_line_id) }, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
return cursor;
}
public boolean updateShip(long id, String name, long cruise_line_id) {
ContentValues args = new ContentValues();
args.put(C_NAME, name);
args.put(C_CRUISE_LINE, cruise_line_id);
return db.update(TABLE, args, C_ID + " = ?", new String[] { String.valueOf(id) }) > 0;
}
public boolean updateShip(ShipModel ship) {
return updateShip(ship.getId(), ship.getName(), ship.getCruiseLineId());
}
public boolean deleteShip(long id) {
return db.delete(TABLE, C_ID + " = ?", new String[] { String.valueOf(id) }) > 0;
}
public boolean deleteShip(String name) {
return db.delete(TABLE, C_NAME + " = ?", new String[] { name }) > 0;
}
public boolean deleteShip(ShipModel ship) {
return deleteShip(ship.getName());
}
public boolean deleteAll() {
return db.delete(TABLE, null, null) > 0;
}
private ShipModel cursorToShip(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(C_ID));
String name = cursor.getString(cursor.getColumnIndex(C_NAME));
long cruise_line_id = cursor.getLong(cursor.getColumnIndex(C_CRUISE_LINE));
return new ShipModel(id, name, cruise_line_id);
}
}

SQLitedatabase crash after upgrade

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

Categories