This question already has answers here:
Android column '_id' does not exist?
(8 answers)
Closed 4 years ago.
Can someone assist me in getting my list to populate using setMultiChoiceItems with a cursor? My AlertDialog pops up with the title and buttons, but nothing in the list. I have confirmed there is at least one item in the database and that should show up on the list but it doesn't currently. I think it has something to do with my cursor. Thank you.
String isCheckedColumn;
String labelColumn;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new MyDBHandler(this);
// CHECK INSERTION TO DATABASE WORKS AND PRINT TO LOGCAT
mydb.insertAllergy("Nuts", "0");
ArrayList<String> s = mydb.getAllAllergies();
System.out.println(s.get(0));
// INITIALIZE VARIABLES FOR LIST POPUP
isCheckedColumn = "selected";
labelColumn = "allergy";
}
/** LIST SELECTION POPUP */
public void selectAllergens() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Allergens");
builder.setMultiChoiceItems(cursor, isCheckedColumn, labelColumn, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId, boolean isSelected) {
if(isSelected) {
System.out.println("onClick if");
} else {
System.out.println("onClick else");
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
Dialog dialog = builder.create();
dialog.show();
}
Here's my database helper class, MyDBHandler. I thought maybe there should be a getCursor method here so when I need to initialize a cursor I can do it with that. It didn't work.
public class MyDBHandler extends SQLiteOpenHelper {
// DATABASE INFORMATION
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "AllergiesDB.db";
private static final String TABLE_NAME = "allergies_list";
private static final String COLUMN_ID = "allergy_id";
private static final String COLUMN_ALLERGY = "allergy";
private static final String COLUMN_SELECTED = "selected";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_ALLERGY + " TEXT, " + COLUMN_SELECTED + " TEXT)";
// INITIALIZE DATABASE
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertAllergy(String allergy, String isChecked) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ALLERGY, allergy);
contentValues.put(COLUMN_SELECTED, isChecked);
db.insert(TABLE_NAME, null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + COLUMN_ID + "=" + id + "", null);
return cursor;
}
public boolean updateAllergies(Integer id, String allergy, String isChecked) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ALLERGY, allergy);
contentValues.put(COLUMN_SELECTED, isChecked);
db.update(TABLE_NAME, contentValues, "id = ? ", new String[] {Integer.toString(id)});
return true;
}
public Integer deleteAllergy(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "id = ? ", new String[] {Integer.toString(id)});
}
public ArrayList<String> getAllAllergies() {
ArrayList<String> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
while(cursor.isAfterLast() == false) {
array_list.add(cursor.getString(cursor.getColumnIndex(COLUMN_ALLERGY)));
cursor.moveToNext();
}
return array_list;
}
public ArrayList<String> getSelectedAllergies() {
ArrayList<String> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
while(cursor.isAfterLast() == false) {
array_list.add(cursor.getString(cursor.getColumnIndex(COLUMN_SELECTED)));
cursor.moveToNext();
}
return array_list;
}
public Cursor getCursor() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
return cursor;
}
}
This is what the popup looks like:
AlertDialog Popup
Here's the error when using 'cursor = mydb.getCursor();'. Clicking on the button that opens the AlertDialog produces the error. The cursor initialization is in the onCreate method of the MainActivity so the initialization isn't causing the crash. The use of the cursor in setMultiChoiceItems is the cause, leading me to believe the cursor wasn't initialized properly.
--------- beginning of crash
08-24 20:53:50.330 11277-11277/com.healthydreams.lpa.allergyscanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.healthydreams.lpa.allergyscanner, PID: 11277
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalArgumentException: column '_id' does not exist. Available columns: [allergy_id, allergy, selected]
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:340)
at android.widget.CursorAdapter.init(CursorAdapter.java:180)
at android.widget.CursorAdapter.<init>(CursorAdapter.java:144)
at android.support.v7.app.AlertController$AlertParams$2.<init>(AlertController.java:1009)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:1009)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:965)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:982)
at com.healthydreams.lpa.allergyscanner.MainActivity.selectAllergens(MainActivity.java:148)
at com.healthydreams.lpa.allergyscanner.MainActivity.openProfiles(MainActivity.java:85)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I assume when you first ran your code you would have got colum_id exception. column '_id' does not exist and the app would have crashed. What this means is you would have to create your primary key like this _columnId. See the underscore at the start. You can read more about the why here. But for now, remember sqllite needs the _ at the start of the primary key column.
About "_id" field in Android SQLite
Once you have done that change, next you would face a problem with the select query in your getCursor() method. Sometimes the * does not work as it needs the explicit name of your columns, so change the query to
select " + COLUMN_ID + "," + COLUMN_ALLERGY + "," + COLUMN_SELECTED + " from " + TABLE_NAME
I am posting these changes below, I have not called any other method as I wanted to give you a start where you are not seeing crashes in the app.
private static final String COLUMN_ID = " _columnId";
private static final String COLUMN_ALLERGY = "allergy";
private static final String COLUMN_SELECTED = "selected";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + COLUMN_ID " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_ALLERGY + ", " + COLUMN_SELECTED + ")";
......
public Cursor getCursor() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select " + COLUMN_ID + "," +
COLUMN_ALLERGY + "," + COLUMN_SELECTED + " from " + TABLE_NAME,
null);
cursor.moveToFirst();
return cursor;
}
You can call the method which would populate data in the database and then call the getCursor method. Once you have that, entries would appear in the dialog box.
Let me know if you face any issue.
Related
I am currently doing an Android application with a SQLite database and I want to create a method that will retrieve all tasks that are associated to one owner, but the application cannot retrieve them but instead return me an exception. How can I solve this?
This is the code for the database:
public class SchedulerDbHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "scheduler.db";
public static final String TABLE_NAME = "SCHEDULER_TABLE";
public static final String TASK_NAME = "NAME";
public static final String TASK_YEAR = "YEAR";
public static final String TASK_MONTH = "MONTH";
public static final String TASK_DAY = "DAY";
public static final String TASK_HOUR = "HOUR";
public static final String TASK_MINUTE = "MINUTE";
public static final String TASK_DESCRIPTION = "DESCRIPTION";
public static final String TASK_OWNER = "OWNER";
public SchedulerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query = "CREATE TABLE " + TABLE_NAME + "(" + TASK_NAME + " TEXT PRIMARY KEY, " +
TASK_YEAR + " INTEGER, " + TASK_MONTH + " INTEGER, " + TASK_DAY + " INTEGER, " +
TASK_HOUR + " INTEGER, " + TASK_MINUTE + " INTEGER, " + TASK_DESCRIPTION + " TEXT, " +
TASK_OWNER + " TEXT" + ")";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
sqLiteDatabase.execSQL(query);
onCreate(sqLiteDatabase);
}
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_NAME, task.getTaskName());
values.put(TASK_YEAR, task.getYear());
values.put(TASK_MONTH, task.getMonth());
values.put(TASK_DAY, task.getDay());
values.put(TASK_HOUR, task.getHour());
values.put(TASK_MINUTE, task.getMinute());
values.put(TASK_DESCRIPTION, task.getDescription());
values.put(TASK_OWNER, loginID);
db.insert(TABLE_NAME, null, values);
db.close();
}
public Task getTask(String taskName){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{TASK_NAME, TASK_YEAR, TASK_MONTH, TASK_DAY, TASK_HOUR, TASK_MINUTE, TASK_DESCRIPTION, TASK_OWNER}, TASK_NAME + " =?",
new String[]{taskName}, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
}
Task task = new Task(cursor.getString(0), Integer.parseInt(cursor.getString(1)), Integer.parseInt(cursor.getString(2)),
Integer.parseInt(cursor.getString(3)), Integer.parseInt(cursor.getString(4)), Integer.parseInt(cursor.getString(5)),
cursor.getString(6)) ;
return task;
}
public ArrayList<Task> getAllTask(){
ArrayList<Task> taskList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setTaskName(cursor.getString(0));
task.setYear(Integer.parseInt(cursor.getString(1)));
task.setMonth(Integer.parseInt(cursor.getString(2)));
task.setDay(Integer.parseInt(cursor.getString(3)));
task.setHour(Integer.parseInt(cursor.getString(4)));
task.setMinute(Integer.parseInt(cursor.getString(5)));
task.setDescription(cursor.getString(6));
taskList.add(task);
} while (cursor.moveToNext());
}
return taskList;
}
public int updateTask(Task task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_NAME, task.getTaskName());
values.put(TASK_YEAR, task.getYear());
values.put(TASK_MONTH, task.getMonth());
values.put(TASK_DAY, task.getDay());
values.put(TASK_HOUR, task.getHour());
values.put(TASK_MINUTE, task.getMinute());
values.put(TASK_DESCRIPTION, task.getDescription());
return db.update(TABLE_NAME, values, TASK_NAME + "=?", new String[]{task.getTaskName()});
}
public void deleteTask(Task task){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, TASK_NAME + "=?", new String[]{task.getTaskName()});
db.close();
}
public int getTaskCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
public ArrayList<Task> getAllTaskForUser(){
ArrayList<Task> taskList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + TASK_OWNER + " = " + loginID;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setTaskName(cursor.getString(0));
task.setYear(Integer.parseInt(cursor.getString(1)));
task.setMonth(Integer.parseInt(cursor.getString(2)));
task.setDay(Integer.parseInt(cursor.getString(3)));
task.setHour(Integer.parseInt(cursor.getString(4)));
task.setMinute(Integer.parseInt(cursor.getString(5)));
task.setDescription(cursor.getString(6));
taskList.add(task);
loginID = cursor.getString(7);
} while (cursor.moveToNext());
}
return taskList;
}
}
This is the code for the main fragment running the database:
public class SchedulerFragment extends android.support.v4.app.Fragment {
ListView listViewTaskList;
ArrayList<Task> taskList;
SchedulerDbHelper taskDb;
public static String taskPrimary;
public SchedulerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_scheduler, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Scheduler");
taskDb = new SchedulerDbHelper(getActivity());
taskList = taskDb.getAllTaskForUser();
Iterator<Task> i = taskList.iterator();
String[] taskNameArray = new String[taskList.size()];
int index = 0;
FloatingActionButton floatingActionButtonNewTask = getView().findViewById(R.id.floatingActionButtonNewTask);
listViewTaskList = getView().findViewById(R.id.listViewTaskList);
while(i.hasNext()){
Task t = i.next();
taskNameArray[index] = t.getTaskName();
index++;
}
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, taskNameArray);
listViewTaskList.setAdapter(adapter);
} catch (RuntimeException r1) {
}
listViewTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String taskName = adapterView.getItemAtPosition(i).toString();
taskPrimary = taskName;
TaskDetailFragment tdf = new TaskDetailFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.frameLayoutContent, tdf, tdf.getTag()).commit();
}
});
floatingActionButtonNewTask.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
NewSchedulerFragment nsf = new NewSchedulerFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.frameLayoutContent, nsf, nsf.getTag()).commit();
}
});
}
}
And this is the exception that I got:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.eduhub, PID: 6873
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.eduhub/com.example.android.eduhub.ContentMainActivity}: android.database.sqlite.SQLiteException: no such column: tth980409 (code 1): , while compiling: SELECT * FROM SCHEDULER_TABLE WHERE OWNER = tth980409
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.database.sqlite.SQLiteException: no such column: tth980409 (code 1): , while compiling: SELECT * FROM SCHEDULER_TABLE WHERE OWNER = tth980409
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
at com.example.android.eduhub.SchedulerDbHelper.getAllTaskForUser(SchedulerDbHelper.java:143)
at com.example.android.eduhub.SchedulerFragment.onViewCreated(SchedulerFragment.java:55)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1430)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6679)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Application terminated.
Value needs to be in quotes.
Update your query to
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + TASK_OWNER + " = " + "\"" + loginID + "\"";
I've created a class which extends SQLiteOpenHelper class and trying to create a DB and insert a dummy record when my Android app launches.
However I get an error 'table gallery has no column named title'.
No error being thrown for the other columns and they're all created in the same way.
The error:
12-19 14:24:30.401 4801-4807/? E/art: Failed sending reply to debugger: Broken pipe
12-19 14:24:30.808 4801-4801/? E/SQLiteLog: (1) table gallery has no column named title
12-19 14:24:30.810 4801-4801/? E/SQLiteDatabase: Error inserting title=First pic artist=James Liscombe rank=3 year=1992
android.database.sqlite.SQLiteException: table gallery has no column named title (code 1): , while compiling: INSERT INTO gallery(title,artist,rank,year) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.jamesliscombe.cet325assignment.DBHandler.addPicture(DBHandler.java:59)
at com.example.jamesliscombe.cet325assignment.Home.onCreate(Home.java:35)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The class I've created which extends SQLiteOpenHelper:
public class DBHandler extends SQLiteOpenHelper {
//DB Info
private static final int DB_VERSION = 2;
private static final String DB_NAME = "louvre";
private static final String TABLE_NAME = "gallery";
//Table column names
private static final String KEY_ID = "id";
private static final String KEY_RANK = "rank";
private static final String KEY_ARTIST = "artist";
private static final String KEY_TITLE = "title";
private static final String KEY_YEAR = "year";
public DBHandler(Context context) {
super(context, DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_GALLERY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + "INTEGER PRIMARY KEY," + KEY_RANK + "INTEGER,"
+ KEY_ARTIST + "TEXT," + KEY_TITLE + "TEXT," + KEY_YEAR + "TEXT" + ")";
db.execSQL(CREATE_GALLERY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//Create table again
onCreate(db);
}
//Adding a new gallery record
public void addPicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
//Insert row
db.insert(TABLE_NAME, null, values);
//Close db connection
db.close();
}
//Reading a single record
public Picture getPicture(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {
KEY_ID,KEY_RANK,KEY_ARTIST,KEY_TITLE,KEY_YEAR
},KEY_ID + "=?", new String[] {
String.valueOf(id) }, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Picture contact = new Picture(Integer.parseInt(cursor.getString(0)),Integer.parseInt(cursor.getString(1)),cursor.getString(2),cursor.getString(3), cursor.getString(4));
return contact;
}
//Reading all records
public List<Picture> getAllPictures() {
List<Picture> galleryList = new ArrayList<Picture>();
//Select all query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loop through all rows and add to galleryList.
if(cursor.moveToFirst()) {
do {
Picture picture = new Picture();
picture.setId(Integer.parseInt(cursor.getString(0)));
picture.setRank(Integer.parseInt(cursor.getString(1)));
picture.setArtist(cursor.getString(2));
picture.setTitle(cursor.getString(3));
picture.setYear(cursor.getString(4));
galleryList.add(picture);
} while (cursor.moveToNext());
}
return galleryList;
}
//Get total number of records
public int getGallerySize() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
//Update gallery items
public int updateGallery(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
return db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(picture.getId())});
}
//Delete a gallery record
public void deletePicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] {String.valueOf(picture.getId())});
db.close();
}
}
Where I'm using the class and inserting a dummy record:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Create our DB
DBHandler db = new DBHandler(this);
//Insert some test data into our db
db.addPicture(new Picture(1,3,"James","First pic","1992"));
You already have a database installed in your device that does not contain title column so when your try to add the dummy data with the value for Title column, you get the error.
This can be fixed by deleting the old already created database and then running your application again so that new database is created.
To delete the existing database, go to Android Device Monitor -> data -> data and then search for your app's package name. Click on your app's package name and then delete the database folder inside it and then run your app again.
I'm trying to login using the database by using the id of the specific members.
But the app crashes with log error.
Following various other similar errors, I included "c1.movetoFirst();" and "c2.movetoFirst();". But still its not working.
The logcat error is:
FATAL EXCEPTION: main
Process: no.nordicsemi.android.nrftoolbox, PID: 13196
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: java.lang.reflect.InvocationTargetException
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:432)
at android.database.AbstractWindowedCursor.checkPosition
at android.database.AbstractWindowedCursor.getInt
at no.nordicsemi.android.nrftoolbox.LoginActivity.login
The LoginActivity is :
public class LoginActivity extends AppCompatActivity {
TextView email;
TextView pass;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (TextView) findViewById(R.id.editText_mail);
pass = (TextView) findViewById(R.id.editText_pass);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
}
public void register(View v) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Register_Page.class);
startActivity(goToSecond);
}
public void login(View v) {
Cursor c1 = mydb.getEmail(email);
c1.moveToFirst();
Cursor c2 = mydb.getpass(pass);
c2.moveToFirst();
int id1=c1.getInt(0);
int id2=c2.getInt(0);
if (id1>0 & id2>0) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Profile.class);
startActivity(goToSecond);
} else
message(getApplicationContext(), "not valid user");
}
}
The myDbHelper is:
public class myDbAdapter extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_PASS = "password";
public static final String CONTACTS_COLUMN_DOB = "dateofbirth";
public static final String CONTACTS_COLUMN_GENDER = "gender";
public static final String CONTACTS_COLUMN_PHONE="phone";
public static final String CONTACTS_COLUMN_CITY="city";
public static final String CONTACTS_COLUMN_WALLET="wallet";
private HashMap hp;
public myDbAdapter(Context context) {
super(context, DATABASE_NAME , null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + CONTACTS_TABLE_NAME + "(" + CONTACTS_COLUMN_ID + " INTEGER PRIMARY KEY," + CONTACTS_COLUMN_NAME + " TEXT," + CONTACTS_COLUMN_EMAIL + " TEXT," + CONTACTS_COLUMN_PASS +" TEXT," + CONTACTS_COLUMN_DOB + " TEXT," + CONTACTS_COLUMN_GENDER + " TEXT," + CONTACTS_COLUMN_PHONE + " INTEGER," + CONTACTS_COLUMN_CITY + " TEXT,"+CONTACTS_COLUMN_WALLET + " INTEGER DEFAULT 0);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String email, String pass, String dob, String gender, String phone, String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("dateofbirth", dob);
contentValues.put("gender", gender);
contentValues.put("phone", phone);
contentValues.put("city", city);
db.insert("contacts", null, contentValues);
return true;
}
//Cursor csr = no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.getAllRowsFromTable(db,"contacts",true,null)
//no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.LogCursorData(csr);
public int updateWallet(String amount,Integer id)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("wallet",amount);
return(db.update("contacts",contentValues,"id = ? ",new String[] { Integer.toString(id)}));
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public Cursor getEmail(TextView email)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where email='"+email.getText().toString()+"'",null);
return cursor;
}
public Cursor getpass(TextView pass)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where password='"+pass.getText().toString()+"'",null);
return cursor;
}
}
Where is the error? And how can it be recitified?
You better check whether cursor has next before invoking movetoFirst as in
Cursor c1 = mydb.getEmail(email);
if(c1.getcount() > 0)
c1.moveToFirst();
and make sure, email id is already in database and check for case sensitive.
I get following error in logcat when trying to retrieve all SQLite rows from SQLiteOpenHelper.
Caused by: java.lang.NullPointerException at notes.dev.tauhid.com.mynotes.fragment.MyNotes.onCreateView(MyNotes.java:89)
My SQLiteOpenHelper class is
public class DatabaseHandlerNotes extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "my_notes";
private static final String TABLE_NOTES = "my_notes_table";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_DESCRIPTION = "phone_number";
private static final String KEY_DATE = "date";
private static final String KEY_REMINDER_DATE = "reminder_date";
private static final String KEY_CATEGORY = "category";
private static final String KEY_LOCK = "lock";
public DatabaseHandlerNotes(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE " + TABLE_NOTES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_DATE + " INTEGER," + KEY_REMINDER_DATE + " INTEGER," + KEY_CATEGORY + " INTEGER," + KEY_LOCK + " TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
}
public void addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
db.insert(TABLE_NOTES, null, values);
db.close();
}
public Note getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_DATE, KEY_REMINDER_DATE, KEY_CATEGORY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Note note = new Note(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)), Integer.parseInt(cursor.getString(4)), Integer.parseInt(cursor.getString(5)), cursor.getString(6));
return note;
}
public List<Note> getAllNotes() {
List<Note> noteList = new ArrayList<Note>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note note = new Note();
note.setID(Integer.parseInt(cursor.getString(0)));
note.setTitle(cursor.getString(1));
note.setDescription(cursor.getString(2));
note.setDate(Integer.parseInt(cursor.getString(3)));
note.setReminderDate(Integer.parseInt(cursor.getString(4)));
note.setCategory(Integer.parseInt(cursor.getString(5)));
note.setLock(cursor.getString(6));
noteList.add(note);
} while (cursor.moveToNext());
}
return noteList;
}
public int updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
}
public void deleteNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
db.close();
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
And in my Fragment class where i want to retrieve all rows
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_notes_fragment_notes, container, false);
ListView allNotes = (ListView) rootView.findViewById(R.id.my_notes_all);
List<Note> noteList = databaseHandlerNote.getAllNotes();
for (Note note : noteList) {
Note noteEach = new Note();
noteEach.setID(note.getID());
noteEach.setTitle(note.getTitle());
noteEach.setDescription(note.getDescription());
noteEach.setCategory(note.getCategory());
noteEach.setLock(note.getLock());
noteEach.setDate(note.getDate());
noteEach.setReminderDate(note.getReminderDate());
this.customNotesList.add(noteEach);
}
customNoteAdapter = new CustomNoteAdapter(getActivity(), customNotesList);
allNotes.setAdapter(customNoteAdapter);
return rootView;
}
Here 89th line in onCreateView is
List<Note> noteList = databaseHandlerNote.getAllNotes();
Thanks in advance.
The problem is that onActivityCreated() is called after onCreateView(). Thus your databaseHandlerNote hasn't been created yet, and trying to use it will result in a NullPointerException.
Check out the Fragment lifecycle diagram from the Fragment documentation.
From Fragment lifecircle, onCreateView() is called before onActivityCreated(), so when you call:
List<Note> noteList = databaseHandlerNote.getAllNotes();
in onCreateView(), databaseHandlerNote is not yet created, then you got exception. So solution is that:
move your:
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
from onActivityCreated() to onCreate()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Im trying to store data from some editTexts on a local android database and then eventually show it on a listview, but right now Im getting an error that says a column doesnt exist, I was following a tutorial on android hive so some of the variable names might look weird, but everything should be accurate.
StackTrace
2038-12038/com.example.adrian.legioncheck_in E/SQLiteLog﹕ (1) table contacts has no column named Longitude
08-25 12:12:19.121 12038-12038/com.example.adrian.legioncheck_in E/SQLiteDatabase﹕ Error inserting Latitude=-85 Longitude=50 POnumber=255902
android.database.sqlite.SQLiteException: table contacts has no column named Longitude (code 1): , while compiling: INSERT INTO contacts(Latitude,Longitude,POnumber) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1523)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
at com.example.adrian.legioncheck_in.DatabaseHandler.addContact(DatabaseHandler.java:67)
at com.example.adrian.legioncheck_in.MapsActivity.SaveAction(MapsActivity.java:67)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3850)
at android.view.View.performClick(View.java:4470)
at android.view.View$PerformClick.run(View.java:18593)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Database Handle.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// 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
private static final String KEY_ID = "id";
private static final String KEY_NAME = "POnumber";
private static final String KEY_PH_NO = "Latitude";
private static final String KEY_LONG = "Longitude";
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,"
+ KEY_PH_NO + " TEXT" + KEY_LONG + " 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);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
/* line 67 */ void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_LONG }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setPO(cursor.getString(1));
contact.setLat(cursor.getString(2));
contact.setLong(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
contact.java
public class Contact {
//private variables
int _id;
String _PO;
String _lat;
String _longi;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String PO, String _lat, String _longi){
this._id = id;
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// constructor
public Contact(String PO, String _lat, String _longi){
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getPO(){
return this._PO;
}
// setting name
public void setPO(String PO){
this._PO = PO;
}
// getting phone number
public String getLat(){
return this._lat;
}
// setting phone number
public void setLat(String lat){
this._lat = lat;
}
public String getLong()
{
return this._longi;
}
public void setLong(String longi)
{
this._longi = longi;
}
}
Button that saves data to database:
public void SaveAction(View view)
{
EditText po = (EditText)findViewById(R.id.POnumber);
String PO = po.getText().toString();
EditText textlat = (EditText)findViewById(R.id.textLat);
String LAT = textlat.getText().toString();
EditText textlong = (EditText)findViewById(R.id.textLong);
String LONG = textlong.getText().toString();
DatabaseHandler db = new DatabaseHandler(MapsActivity.this);
db.addContact(new Contact(PO,LAT,LONG));
// Reading all Data
Log.d("Reading: ", "Reading all inputs..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,PO number: " + cn.getPO() + " ,Latitude: " + cn.getLat() + " ,Longitude: " + cn.getLong();
// Writing Data to log
Log.d("Name: ", log);
}
}
KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")"
Add the missing , before KEY_LONG:
KEY_PH_NO + " TEXT," + KEY_LONG + " TEXT" +")"
Uninstall your app so the onCreate() is run again. See
When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more about that.