Android application crashing when inserting row to SQlite? - java

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

Related

Error: Attempt to invoke virtual method on null object reference 'android.database.Cursor com.myapplication.DatabaseHeleper.getData()'

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

where clause is not working in sqlite database [duplicate]

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

How to fix IndexOutOfBoundsException : invalid index 0 size is 0

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

How do you search or sort in SQLite Database?

I have an application that stores information in a database based on the information from 5 text fields. I'm having trouble being able to sort through fields or just even sorting from one field. Also, what method does the ORDER BY clause go in? Snippets of code for the database is below:
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String lastName = "lastName";
public static final String firstName = "firstName";
public static final String school = "school";
public static final String email = "email";
public static final String intrest = "intrest";
Cursor d = sqLiteDatabase.rawQuery("SELECT * from " + MYDATABASE_TABLE + "ORDER BY " + lastName + " ASC" , null);
while (d.moveToNext()) {
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(intrest);
String lastName = d.getString(sort);
String intrest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + intrest);
}
Try to use (cursor.getCount() > 0) method and (cursor != null) condition in your code to check whether you gets data or not. That I have shown below. and try to use Log for your query for the perfection and put that query in your sqlite database to check whether it is working properly or not.
Cursor d = sqLiteDatabase.rawQuery("SELECT * from " + MYDATABASE_TABLE + " ORDER BY " + lastName + " ASC" , null); // here I have edited space before ORDER BY word starts. Please note this
Log.d("query",">>>>"+SELECT * from " + MYDATABASE_TABLE + " ORDER BY " + lastName + " ASC"); // check this query is going to right way or not using local database.
if(d != null){
if(d.getCount() > 0){ // to check you get one or more data
d.moveToFirst();
do{
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(intrest);
String lastName = d.getString(sort);
String intrest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + intrest);
} while (d.moveToNext());
}
}
Try this. Hope it will help you.
I like query method better, because it's more clear:
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String lastName = "lastName";
public static final String firstName = "firstName";
public static final String school = "school";
public static final String email = "email";
public static final String interest = "interest";
public final String[] columns = new String[] {
lastName,
firstName,
school,
email,
interest
};
public void printInOrder(String column) {
Cursor d = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null, null, null, null, column + " ASC");
while (d.moveToNext()) {
int sort = d.getColumnIndex(lastName);
int sort2 = d.getColumnIndex(interest);
String lastName = d.getString(sort);
String interest = d.getString(sort2);
System.out.println("GOT STUDENT " + lastName + " LIKES " + interest);
}
}

android.database.sqlite.SQLiteConstraintException can not be fixed

I have a insertion method which cheks first if the row is available or not, if not then it tries to create new or if available then it updates that, but this method giving me the exception in the else part, here is my method
public long SetSettings(String whichCol, String value) {
// TODO Auto-generated method stub
preferences = ourcontext.getSharedPreferences(filenames, 0);
String[] colum = new String[] { KEY_CAR };
Cursor c = ourDB.query(DBhelper.DATABASE_SETTINGSTABLE, colum, KEY_CAR
+ "=" + "'" + preferences.getString("selectedcar", "") + "'",
null, null, null, null);
ContentValues cvedit = new ContentValues();
cvedit.put(KEY_CAR, preferences.getString("selectedcar", ""));
cvedit.put(whichCol, value);
if (c.getCount() > 0) {
return ourDB.update(
DBhelper.DATABASE_SETTINGSTABLE,
cvedit,
KEY_CAR + "=" + "'"
+ preferences.getString("selectedcar", ""), null);
} else {
return ourDB.insert(DBhelper.DATABASE_SETTINGSTABLE, null, cvedit);
}
}
and this is how I created my database:
public static final String KEY_ID = "_id";
public static final String KEY_CAR = "car";
public static final String KEY_SET_DISENTRY_MODE = "ditance_entry_mode";
public static final String KEY_SET_DISUNIT = "distance_unit";
public static final String KEY_SET_PETROLUNIT = "petrol_unit";
public static final String KEY_SET_CONDISPLAY = "consumption_display";
public static final String KEY_SET_DATEFORMAT = "date_format";
public static final String KEY_SET_CURRENCY = "currency";
public static final String KEY_SET_STOREFILLLOC = "store_fillloc";
public static final String KEY_SET_GPSPIN = "gps_pin";
public static final String KEY_SET_KEYCLICK = "keyboard_click";
public static final String KEY_SET_KEYVIBRATE = "keyboard_vibrate";
public static final String KEY_SET_BACKUP = "backup";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_SETTINGSTABLE + " (" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_CAR
+ " TEXT NOT NULL, " + KEY_SET_DISENTRY_MODE + " TEXT, "
+ KEY_SET_DISUNIT + " TEXT, " + KEY_SET_PETROLUNIT + " TEXT, "
+ KEY_SET_CONDISPLAY + " TEXT, " + KEY_SET_DATEFORMAT
+ " TEXT, " + KEY_SET_CURRENCY + " TEXT, "
+ KEY_SET_STOREFILLLOC + " TEXT, " + KEY_SET_GPSPIN + " TEXT, "
+ KEY_SET_KEYCLICK + " TEXT, " + KEY_SET_KEYVIBRATE + " TEXT, "
+ KEY_SET_BACKUP + " TEXT NOT NULL);");
}
I cant figure out where is my problem, any help?
you have a constraint KEY_SET_BACKUP TEXT NOT NULL but when updating you are passing null as this value, so add below line too to the contentvalues
cvedit.put(KEY_SET_BACKUP,"");

Categories