Interchange ids of android database - java

How to go about if i want to interchange the contents of my android data base as shown below:
before
1 hello world
2 Android Nougat
after
1 Android Nougat
2 hello world

You don't need to change the positions in Database. You need to add additional int value to a database (not id). And change this value according to a new position. For first object you make it 2; for a second - 1. And when you retrieve data from your database you just sort it according to this value.
Example
String orderBy = "POSITION ASC";
Cursor cursor = database.query(TABLE_NAME, logTableColumns, null, null,
null, null, orderBy);

public class QueueDatabase extends SQLiteOpenHelper {
public QueueDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "queue.sqlite";
//Table names
public static final String TABLE_QUEUE = "Queue";
public static final String KEY_ID = "id";
public static final String KEY_SNAME = "key_sname";
public static final String KEY_ANAME = "key_aname";
public static final String KEY_URL = "key_url";
public static final String KEY_ORDER = "key_order";
public static final String CREATE_TABLE_QUEUE= "CREATE TABLE IF NOT EXISTS "
+ TABLE_QUEUE
+ "("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_SNAME
+ " TEXT,"
+ KEY_ANAME
+ " TEXT,"
+ KEY_URL
+ " TEXT,"
+ KEY_ORDER
+ " TEXT "
+")";
public long insertQueue(ArrayList<Music> mTaskArr)
{
long row_id = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i = 0;i<mTaskArr.size() ;i++) {
values.put(KEY_SNAME, mTaskArr.get(i).getTitle());
values.put(KEY_ANAME, mTaskArr.get(i).getArtist());
values.put(KEY_URL, mTaskArr.get(i).getUrl());
row_id = db.insert(TABLE_QUEUE, null, values);
}
db.close();
return row_id;
}
public void updateOrder(long rowID, int newPos) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ORDER, newPos);
db.update(TABLE_QUEUE, cv, KEY_ID + "=" + rowID, null);
}
public boolean updateQueue (Integer id, String S, String A, String U) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SNAME,S);
contentValues.put(KEY_ANAME,A);
contentValues.put(KEY_URL,U);
db.update(TABLE_QUEUE, contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public void dropTable() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "drop table " + TABLE_QUEUE;
try {
db.execSQL(sql);
} catch (SQLException e) {
System.out.println(e);
}
}
public ArrayList<Music> getAllQueue() {
ArrayList<Music> ar = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_QUEUE;
//Log.d("QUERY",""+selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Music r = new Music();
r.setId(c.getInt(c.getColumnIndex(KEY_ID)));
r.setTitle( c.getString(c.getColumnIndex(KEY_SNAME)));
r.setArtist( c.getString(c.getColumnIndex(KEY_ANAME)));
r.setUrl(c.getString(c.getColumnIndex(KEY_URL)));
ar.add(r);
} while (c.moveToNext());
}
db.close();
return ar;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUEUE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void arrange() {
SQLiteDatabase db = this.getWritableDatabase();
String[] rank = new String[]{ QueueDatabase.KEY_ID };
Cursor c = db.query(QueueDatabase.TABLE_QUEUE, rank, null, null, null, null, QueueDatabase.KEY_ORDER+" ASC");
}
}
this is how u enter data in database:
q.add(new Music(T, U, A));
qd.insertQueue(q);

Related

SQLite Database Error - No column named task

Error_Database
enter code here
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String NAME = "toDoListDatabase";
private static final String TODO_TABLE = "todo";
private static final String ID = "id";
private static final String TASK = "task";
private static final String STATUS = "status";
private static final String CREATE_TODO_TABLE = "CREATE TABLE " + TODO_TABLE + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TASK + " TEXT, "
+ STATUS + " INTEGER)";
private SQLiteDatabase db;
public DataBaseHandler(Context context) {
super(context, NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE);
// Create tables again
onCreate(db);
}
public void openDatabase() {
db = this.getWritableDatabase();
}
public void insertTask(ToDoModel task){
ContentValues cv = new ContentValues();
cv.put(TASK, task.getTask());
cv.put(STATUS, 0);
db.insert(TODO_TABLE, null, cv);
}
public List<ToDoModel> getAllTasks(){
List<ToDoModel> taskList = new ArrayList<>();
Cursor cur = null;
db.beginTransaction();
try{
cur = db.query(TODO_TABLE, null, null, null, null, null, null, null);
if(cur != null){
if(cur.moveToFirst()){
do{
ToDoModel task = new ToDoModel();
task.setId(cur.getInt(cur.getColumnIndexOrThrow(ID)));
task.setTask(cur.getString(cur.getColumnIndexOrThrow(TASK)));
task.setStatus(cur.getInt(cur.getColumnIndexOrThrow(STATUS)));
taskList.add(task);
}
while(cur.moveToNext());
}
}
}
finally {
db.endTransaction();
assert cur != null;
cur.close();
}
return taskList;
}
public void updateStatus(int id, int status){
ContentValues cv = new ContentValues();
cv.put(STATUS, status);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void updateTask(int id, String task) {
ContentValues cv = new ContentValues();
cv.put(TASK, task);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void deleteTask(int id){
db.delete(TODO_TABLE, ID + "= ?", new String[] {String.valueOf(id)});
}
}
Can somebody proofread this? The error is :
"no column named task in "INSERT INTO todo(status,task) VALUES (?,?)"
"android.database.sqlite.SQLiteException: table todo has no column named task (code 1 SQLITE_ERROR): , while compiling: INSERT INTO todo(status,task) VALUES (?,?)".
I also attached a ss of the error as a link.
I'm trying to create a database where I can store tasks. Does anyone has a fix for this?
Thanks!
If you're on an emulator, try reinstalling the application! It works sometimes.

Returning SQLite query and returning as text

I have a query (getMinScore) which takes the min value from my table, I need to take this and display it in a text field but in it's current state it displays
High Score: android.database.SQLiteCursor#.......
I don't know what this means, how can I get the string value from this?
I am calling the query from my GameView class as in the second block of code. Really appreciate any help!
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
long result = db.insert(TABLE_NAME, null, contentValues);
System.out.println("Data inserted" + score);
if(result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java
String minScore = mydb.getMinScore().toString();
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(40);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: " + mydb.getMinScore(), 10, 1280, tp);
A Cursor is an object that gives you access to the results of a database query by iterating over the rows. You can't just print out the cursor, you need to check if there is a next row and then pull the value out from it.
You could change your getMinScore method to return the minScore value instead of returning the cursor:
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if(res.moveToNext()) {
// return the integer from the first column
return res.getInt(0);
} else {
// there were no results
return -1;
}
}
Have a read of the documentation to understand the cursor methods.
You have to get your value from the returning Cursor object. In your case you can use
int score = res.getInt(res.getColumnIndex("SCORE"));
Be sure to check the returning cursor is not NULL by checking cursor count > ZERO.
Change your method
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
To
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.getCount() > 0) {
return res.getInt(res.getColumnIndex("SCORE"));
} else {
return -1; // Some defualt value when no data is retrieved
}
}
you Should always close Cursor to prevent memory leak
so
public int getMinScore() {
int result = -1;
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.moveToFirst()) {
result = res.getInt(0);
}
if (!res.isClosed()){
res.close();
}
return result;
}
}
i think it better to user method open and close instead of calling getWritableDatabase() every time
public void open() {
bdd = dbHelper.getWritableDatabase();
}
public void close() {
bdd.close();
}

Android SQLite Table Creation Error

I have my code to create SQLite database, the code create database but does not create any table. I went through some of the similar errors that others had before, I couldn't find any error. Could anyone help me.
Here is my code
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "swahilComm.db";
public static final String COUNTRY_TABLE = "countries";
public static final String COUNTRY_ID = "id";
public static final String COUNTRY_NAME = "country";
public static final String PROVINCE_TABLE = "province";
public static final String PROVINCE_ID = "id";
public static final String PROVINCE_NAME = "province";
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operation", "Database Created...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
db.execSQL(CREATE_COUNTRY_TABLE);
Log.d("Database Operation", "Tables Created...");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
db.execSQL("DROP TABLE IF EXISTS " + PROVINCE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTRY_TABLE);
// Create tables again
onCreate(db);
}
//Delete all data in the table
public void DeleteCountry() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COUNTRY_TABLE, null, null);
db.close(); // Closing database connection
}
//Delete all data in the Province table
public void DeleteProvice() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PROVINCE_TABLE, null, null);
db.close(); // Closing database connection
}
//Insert country records
public int insertCountry(Country country) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_ID, country.getId());
values.put(COUNTRY_NAME, country.getCountry());
// Inserting Row
long country_Id = db.insert(COUNTRY_TABLE, null, values);
db.close(); // Closing database connection
return (int) country_Id;
}
//Insert province records
public int insertProvince(Province province) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PROVINCE_ID, province.getId());
values.put(PROVINCE_NAME, province.getProvince());
// Inserting Row
long province_Id = db.insert(PROVINCE_NAME, null, values);
db.close(); // Closing database connection
return (int) province_Id;
}
//Retrieve all records and populate into List<Country>
//This method allow you to retrieve more fields/information into List.
public List<Country> getAllCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<Country> countryList = new ArrayList<Country>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(cursor.getString(cursor.getColumnIndex(COUNTRY_ID)));
country.setCountry(cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
countryList.add(country);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<Province>
//This method allow you to retrieve more fields/information into List.
public List<Province> getAll() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<Province> provinceList = new ArrayList<Province>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getString(cursor.getColumnIndex(PROVINCE_ID)));
province.setProvince(cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
provinceList.add(province);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
//Retrieve all records and populate into List<String>
public List<String> getAllStringCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<String> countryList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
countryList.add(i,cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<String>
public List<String> getAll_Simple() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<String> provinceList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
provinceList.add(i,cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
}
This is the the Activity Class
public class Register extends AppCompatActivity {
DBHelper repo = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
countries = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, countries);
autoCompleteTextView.setAdapter(adapter);
insertDummyData();
loadProvince_Simple();
}
// This class insert data
private void insertDummyData(){
repo.DeleteProvice();
int i = 1;
String[] provinces = {"Prince Edward Island", "Quebec", "Saskatchewan", "Yukon","Northwest Territories", "Ontario", "Nunavut", "Nova Scotia", "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador"};
for(int j=0; j < provinces.length; j++) {
Province province = new Province();
province.setId(Integer.toString(i));
province.setProvince(provinces[j]);
repo.insertProvince(province);
i++;
}
}
//This is the arrayadapter binding method as you can see
private void loadProvince_Simple(){
ArrayAdapter<String> spinnerAdapter;
DBHelper db = new DBHelper(getApplicationContext());
List<String> provinces = db.getAll_Simple();
spinnerAdapter = new ArrayAdapter<String>(Register.this,
android.R.layout.simple_spinner_item, provinces);
prov_spinner.setAdapter(spinnerAdapter);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
Read my comments below:
// TRY TO REMOVE THE SPACE BETWEEN "TEXT" TO THE "(" IN THE LAST LINE OF BOTH STRINGS
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
// YOU WROTE "INTEGET"
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";

edit content in database SQLiteDatabase

I created a database with SQLiteDatabase, everything works fine, except when I want to change the content of some columns .. I'm using db.update, but it seems not work. someone can help me understand what I'm doing wrong? thank you all
public class Note_DBHelper extends SQLiteOpenHelper {
private Context ctx;
//version of database
private static final int version = 1;
//database name
private static final String DB_NAME = "notesDB";
//name of table
private static final String TABLE_NAME = "notes";
//column names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "noteTitle";
private static final String KEY_CONTENT = "noteContent";
private static final String KEY_TESTO = "noteTesto";
private static final String KEY_TXT_COLORE = "noteColore";
private static final String KEY_DATE = "date";
//sql query to creating table in database
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_TITLE+" TEXT NOT NULL, "+KEY_CONTENT+" TEXT NOT NULL,"+KEY_TESTO+" TEXT NOT NULL, "+KEY_TXT_COLORE+" TEXT NOT NULL, "+KEY_DATE+" TEXT);";
//contructor of Note_DBHelper
public Note_DBHelper(Context context) {
super(context, DB_NAME, null, version);
this.ctx = context;
}
//creating the table in database
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
//in case of upgrade we're dropping the old table, and create the new one
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
//function for adding the note to database
public void addNote(String title, String content,String testo, String txt_colore) {
SQLiteDatabase db = this.getWritableDatabase();
//creating the contentValues object
//read more here -> http://developer.android.com/reference/android/content/ContentValues.html
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
//inserting the note to database
db.insert(TABLE_NAME, null, cv);
//closing the database connection
db.close();
//see that all database connection stuff is inside this method
//so we don't need to open and close db connection outside this class
}
//getting all notes
public Cursor getNotes(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO,KEY_TXT_COLORE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNotes2(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_ID, KEY_TITLE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNote(SQLiteDatabase db, int id) {
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO, KEY_TXT_COLORE, KEY_DATE}, KEY_ID + " = ?", new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
return c;
}
public void removeNote(int id) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] { String.valueOf(id) });
db.close();
}
public void updateNote(String title, String content,String testo, String txt_colore, String editTitle) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
db.update(TABLE_NAME, cv, KEY_TITLE + " LIKE '" + editTitle + "'", null);
db.close();
}
Use this
db.update(TABLE_NAME, cv, KEY_ID + "=" + id, null);
then in your createNote class
dbhelper.updateNote(title, content, id);

Android NullpointerException when trying to retrieve data from SQLiteOpenHelper

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

Categories

Resources