I am storing the response of yes|no|maybe into the userrelation table.
For that, I created a table in DBCONTRACT and get the values in a db helper Class.
when I get the values and store into another variable, it throws this error
This the SQL query for the userRelation table
public static abstract class RingeeUserRelationTable implements BaseColumns {
public static final String TABLE_NAME = "user_relation";
public static final String COL1_EVENT_USER_ID = "EVENT_USER_ID";
public static final String COL2_EVENT_ID = "EVENT_ID";
public static final String COL3_RINGEE_USER_ID = "RINGEE_USER_ID";
public static final String COL4_IS_ATTENDING = "IS_ATTENDING";
public static final String COL5_IS_DELETE = "IS_DELETE";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + " INTEGER PRIMARY KEY," + COL1_EVENT_USER_ID + INTEGER_TYPE + COMMA_SEP + COL2_EVENT_ID + INTEGER_TYPE
+ COMMA_SEP + COL3_RINGEE_USER_ID + INTEGER_TYPE + COMMA_SEP + COL4_IS_ATTENDING + INTEGER_TYPE + COMMA_SEP + COL5_IS_DELETE + INTEGER_TYPE + ")";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public static final String RETRIVE_ALL_USER_DATA = "SELECT " + COL1_EVENT_USER_ID + COMMA_SEP + COL2_EVENT_ID + COMMA_SEP + COL3_RINGEE_USER_ID + COMMA_SEP + COL4_IS_ATTENDING + COMMA_SEP
+ COL5_IS_DELETE + " FROM " + TABLE_NAME;
}
This is the code for getting the value and set to userMOS list
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
This is the code for getting the isattending value in the Fragment
context = getActivity().getApplicationContext();
dbHelper = new DatabaseHelper(context);
userMOs = dbHelper.getAllUserRelation();
// I got the error here there is no value in a table but in back end the values are stored
int isAttending = userMOs.get(position).getIsAttending();
I am using this isattending for setting the colour of the yes|no|maybe Button
switch(isAttending)
{
case 1:
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
case 2:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
break;
case 0:
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
break;
}
When I run this project, I get an error: IndexOutOfBoundsException.
Please tell me what is the cause of the error and how to solve this issue
Indexes are 0 based.
Therefore, you need to rewrite your code like so:
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(0));
userMO.setEventId(cursor.getLong(1));
userMO.setRingeeUserId(cursor.getLong(2));
userMO.setIsAttending(cursor.getInt(3));
userMO.setIsDelete(cursor.getInt(4));
userMOs.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Write the following code as shown below:-
public ArrayList<UserMO> getAllUserRelation() {
ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
if (cursor.moveToFirst()) {
do {
UserMO userMO = new UserMO();
userMO.setEventUserId(cursor.getLong(1));
userMO.setEventId(cursor.getLong(2));
userMO.setRingeeUserId(cursor.getLong(3));
userMO.setIsAttending(cursor.getInt(4));
userMO.setIsDelete(cursor.getInt(5));
userMos.add(userMO);
} while (cursor.moveToNext());
cursor.close();
}
return userMOs;
}
Its giving you a Array Index out of bound exception as you have not assign anything to your array list. which I had did by adding this line in your code above.
userMos.add(userMo);
Related
I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.
This the error
I have attached the error above after executing code below mentioned, the code given below is not full code but it targets the main code for which my question is.I am trying to send sms through a variable in which number is stored by fetching from sqlite database. So below code shows that I tried to fetch from dbhelper.java class and store in variable num in sendsms.java class but i think it is not fetching Hence i would request you to see the code and guide where i am wrong for improvement. I hope that now question is clear and sufficient description is given so please help.
sendsms.java
try {
Cursor cursor = databaseHelper.getdata();
while (cursor.moveToNext())
{
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
public void run() {
sms.sendTextMessage(num, null, "Help! I've met with an accident at http://maps.google.com/?q=" + String.valueOf(latitude) + "" +
"," + String.valueOf(longitude), null, null);
dbhelper.java
public static final String TABLE_REGISTER = "signin";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRM_PASSWORD = "CONFIRM_PASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_REGISTER + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " TEXT , " + COL_PHONE + " LONG UNIQUE ," + COL_EMAIL + " VARCHAR UNIQUE," + COL_PASSWORD + " VARCHAR , "
+ COL_CONFIRM_PASSWORD + " VARCHAR ," + COL_NAMEone_CON + " TEXT , "
+ COL_NUMBERone_CON + " LONG UNIQUE ," + COL_NAMEtwo_CON + " TEXT ," + COL_NUMBERtwo_CON + " LONG UNIQUE , "
+ COL_NAMEthree_CON + " TEXT ," + COL_NUMBERthree_CON + " LONG UNIQUE " + ")");
}
public Cursor getdata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select NUMBERONE, NUMBERTWO,NUMBERTHREE from signin ", null);
return cursor;
}
It seems that you have to call getReadableDatabase or getWritableDatabase before you need the data, this is because it takes time to create the database.So, you have to be aware of that.
Also, I wanted to remark that you must cursor.moveToFirst() before you do cursor.moveToNext() on sendsms.java
Please change your code like this:-
try {
Cursor cursor = databaseHelper.getdata();
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm new to Android. I want to add a column in my existing database which already contains some questions. I tried setting some code in the onUpgrade() method using the ALTER command but it is not working. It is gives an error:
ERROR:-
java.lang.RuntimeException: Unable to start activity
ComponentInfo
{com.example.chaitanya.myquiz/
com.example.chaitanya.myquiz.QuestionActivity}:
android.database.sqlite.SQLiteException: no such column: id (code 1):
, while compiling: SELECT * FROM quest where id = '1'
here is the code.
public class QuizHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "bcd";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "qid";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; // correct option
private static final String KEY_OPTA = "opta"; // option a
private static final String KEY_OPTB = "optb"; // option b
private static final String KEY_OPTC = "optc"; // option c
private static final String KEY_ID2 = "id";
private SQLiteDatabase dbase;
public QuizHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase = db;
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT " + KEY_ID2 + " INTEGER)";
db.execSQL(sql);
addQuestion();
// db.close();
}
private void addQuestion() {
Question q1 = new Question("Who is the president of india ?", "narender modi", "hamid ansari", "pranab mukherji", "pranab mukherji",1);
this.addQuestion(q1);
Question q2 = new Question(" Name of the first university of India ?", "Nalanda University", "Takshshila University", "BHU", "Nalanda University",1);
this.addQuestion(q2);
Question q3 = new Question("Which college is awarded as Outstanding Engineering Institute North Award�", "Thapar University", "G.N.D.E.C", "S.L.I.E.T", "G.N.D.E.C",1);
this.addQuestion(q3);
Question q4 = new Question("Name of the first Aircraft Carrier Indian Ship ?", "Samudragupt", "I.N.S. Vikrant", "I.N.S Virat", "I.N.S. Vikrant",1);
this.addQuestion(q4);
Question q5 = new Question("In which town of Punjab the largest grain market of Asia is Available?", "Bathinda", "Khanna", "Ludhiana", "Khanna",1);
this.addQuestion(q5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (newV > oldV) {
db.execSQL("ALTER TABLE " + TABLE_QUEST + " ADD COLUMN " + KEY_ID2 + " INTEGER DEFAULT 0");
}
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
values.put(KEY_ID2,quest.getID());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST + " where " + KEY_ID2 + " = '1' ";
// + KEY_ID2 + " = 1"
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
Log.i("here",cursor.getCount()+"");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
// Log.i("here",cursor.getInt(0)+"");
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
}
Log.i("here",cursor.getCount()+"") gives the 0 value in the output.
If you just want to add a single column into your existing table quest, then no need to call onCreate(db) from onUpgrade() method.
Modify onUpgrade() method as below:
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
if (newV > oldV) {
db.execSQL("ALTER TABLE " + TABLE_QUEST + " ADD COLUMN " + KEY_ID2 + " INTEGER DEFAULT 0");
}
}
I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I know That Database Version Should Increased, I will it, but What should I put in onUpgrade method ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Well the Java doc pretty much explains what needs to be done.
From Java doc
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else it
needs to upgrade to the new schema version.
What we do is , alter the tables whenever we have changed the table schema.
In addition you can also perform some data migration if required. Basically its a hook which you got and you can perform any kind of compatibility logic.
cheers,
Saurav
This is the DBAdapter I'm using, and for some reason when I try to insert a row- the application crashes.
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
static final String KEY_ROWID = "Row ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "E-mail";
static final String PHONENUMBER_COLUMN = "Phone Number";
static final String ADDRESS_COLUMN = "Street Address";
static final String ZIP_COLUMN = "Zip Code";
static final String ARRIVAL_COLUMN = "Arrival Date";
static final String DEPARTURE_COLUMN = "Departure Date";
static final String ROOM_COLUMN = "Room Number";
static final String NOTES_COLUMN = "Notes Area";
public static final String[] ALL_KEYS = new String[] {NAME_COLUMN, EMAIL_COLUMN, PHONENUMBER_COLUMN, ADDRESS_COLUMN, ZIP_COLUMN, ARRIVAL_COLUMN, DEPARTURE_COLUMN, ROOM_COLUMN, NOTES_COLUMN};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_EMAIL = 2;
public static final int COL_PHONENUMBER = 3;
public static final int COL_ADDRESS = 4;
public static final int COL_ZIP = 5;
public static final int COL_ARRIVAL = 6;
public static final int COL_DEPARTURE = 7;
public static final int COL_ROOM = 8;
public static final int COL_NOTES = 9;
// DataBase info:
static final String DATABASE_NAME = "Reservations.db";
static final String DATABASE_TABLE = "Reservations";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT"
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT"
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT"
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String nameValue, String emailValue, String phoneValue, String addressValue, String zipValue, String arrivalValue, String departureValue, String roomValue, String notesValue) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME_COLUMN, nameValue);
initialValues.put(EMAIL_COLUMN, emailValue);
initialValues.put(PHONENUMBER_COLUMN, phoneValue);
initialValues.put(ADDRESS_COLUMN, addressValue);
initialValues.put(ZIP_COLUMN, zipValue);
initialValues.put(ARRIVAL_COLUMN, arrivalValue);
initialValues.put(DEPARTURE_COLUMN, departureValue);
initialValues.put(ROOM_COLUMN, roomValue);
initialValues.put(NOTES_COLUMN, notesValue);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String email, String phone, String address, String zipcode, String arrival, String departure, String room, String notes) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(NAME_COLUMN, name);
newValues.put(EMAIL_COLUMN, email);
newValues.put(ADDRESS_COLUMN, address);
newValues.put(ZIP_COLUMN, zipcode);
newValues.put(ARRIVAL_COLUMN, arrival);
newValues.put(DEPARTURE_COLUMN, departure);
newValues.put(ROOM_COLUMN, room);
newValues.put(NOTES_COLUMN, notes);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Here's the code from my new reservation activity
public void createReservation(View view) {
db.open();
EditText nameText = (EditText)findViewById(R.id.nameText);
String nameValue = nameText.getText().toString();
EditText emailText = (EditText)findViewById(R.id.emailText);
String emailValue = emailText.getText().toString();
EditText phoneNumber = (EditText)findViewById(R.id.phoneNumber);
String phoneValue = phoneNumber.getText().toString();
EditText addressText = (EditText)findViewById(R.id.addressText);
String addressValue = addressText.getText().toString();
EditText zipNumber = (EditText)findViewById(R.id.zipNumber);
String zipValue = zipNumber.getText().toString();
EditText arrivalDate = (EditText)findViewById(R.id.arrivalDate);
String arrivalValue = arrivalDate.getText().toString();
EditText departureDate = (EditText)findViewById(R.id.departureDate);
String departureValue = departureDate.getText().toString();
EditText notesArea = (EditText)findViewById(R.id.notesText);
String notesValue = notesArea.getText().toString();
EditText roomNum = (EditText)findViewById(R.id.roomNum);
String roomValue = roomNum.getText().toString();
db.insertRow(nameValue, emailValue, phoneValue, addressValue, zipValue, arrivalValue, departureValue, roomValue, notesValue);
Toast toast = Toast.makeText(getApplicationContext(), "Creating Reservation", Toast.LENGTH_LONG);
toast.show();
db.close();
}
Any and all help is greatly appreciated. I've tried looking things up online, which is where I found the DBAdapter, but when I use this DBAdapter I feel like I may have messed something up. For example in Android Studio, the Column Numbers give me the inspection warning that the field is never used. However they were included in the original DBAdapter. I feel like I may have made a mistake when adjusting the DBAdapter to fit my needs, but I can't seem to figure out where I went wrong with it. I am very new to Android programming, and have only made one other application before. Any help is appreciated
Your CREATE TABLE actually doesn't create any table, because it's wrong:
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT"
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT"
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT"
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
Should be:
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COLUMN + " TEXT NOT NULL, "
+ EMAIL_COLUMN + " TEXT, " // Mind the comma
+ PHONENUMBER_COLUMN + " TEXT NOT NULL, "
+ ADDRESS_COLUMN + " TEXT, " // Mind the comma
+ ZIP_COLUMN + " TEXT NOT NULL, "
+ ARRIVAL_COLUMN + " TEXT NOT NULL, "
+ DEPARTURE_COLUMN + " TEXT, " // Mind the comma
+ ROOM_COLUMN + " TEXT NOT NULL, "
+ NOTES_COLUMN + " TEXT"
+ ");";
Please not that you don't need and shouldn't use hardcoded column indexes.
This is because if you do a SELECT * ... nobody can predict the column order inside the row.
So, maybe, on a query run the email field has index 2 and on another run it has index 5.
That's why it's bad to use fixed column indexes, better use column names with getColumnIndex.
This code lets me assume you are going to do something bad:
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_EMAIL = 2;
public static final int COL_PHONENUMBER = 3;
public static final int COL_ADDRESS = 4;
public static final int COL_ZIP = 5;
public static final int COL_ARRIVAL = 6;
public static final int COL_DEPARTURE = 7;
public static final int COL_ROOM = 8;
public static final int COL_NOTES = 9;
Instead, use
cursor.getString(cursor.getColumnIndex(YOUR_COLUMN_NAME)); // I used getString, but you'd use the actual column type
Moreover, don't use spaces or hyphens in your column names!
This
// Field Names:
static final String KEY_ROWID = "Row ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "E-mail";
static final String PHONENUMBER_COLUMN = "Phone Number";
static final String ADDRESS_COLUMN = "Street Address";
static final String ZIP_COLUMN = "Zip Code";
static final String ARRIVAL_COLUMN = "Arrival Date";
static final String DEPARTURE_COLUMN = "Departure Date";
static final String ROOM_COLUMN = "Room Number";
static final String NOTES_COLUMN = "Notes Area";
should be:
// Field Names:
static final String KEY_ROWID = "Row_ID";
static final String NAME_COLUMN = "Name";
static final String EMAIL_COLUMN = "eMail";
static final String PHONENUMBER_COLUMN = "Phone_Number";
static final String ADDRESS_COLUMN = "Street_Address";
static final String ZIP_COLUMN = "Zip_Code";
static final String ARRIVAL_COLUMN = "Arrival_Date";
static final String DEPARTURE_COLUMN = "Departure_Date";
static final String ROOM_COLUMN = "Room_Number";
static final String NOTES_COLUMN = "Notes_Area";