Android NullpointerException when trying to retrieve data from SQLiteOpenHelper - java

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

Related

ID won't save in long format in database Sqlite

I'm making an Android Note Taking app, which save a note and display it in list of notes. if you touch each note it show a title and details of it in another layout. i can save note and i can show them in list but my problem is when i try to use intent to show that specific note's title and details.
what is do is use intent.putExtra("ID",...) and get that intent and show the note's detail and title with use of its ID. but i get "android.database.CursorIndexOutOfBoundsException" error and app crash.
this is part of my Note class:
public class Note {
private String Title, Content, Date, Time;
private long ID;
Note(){}
Note(String Title,String Content,String Date,String Time){
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
Note(long ID,String Title,String Content,String Date,String Time) {
this.ID = ID;
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
this is my NoteDataBase:
public class NoteDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
//column name for database tables
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public NoteDataBase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//create table
String query = "CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ID + " INT PRIMARY KEY," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion >= newVersion) {
return;
} else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long addNote(Note note) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
long ID = db.insert(DATABASE_TABLE,"null",c);
//c.put(KEY_ID,ID);
Log.d("Inserted", "addNote: note with id number " + KEY_ID + " has been inserted");
return ID;
}
public Note getNote(long ID){
//Select * from DatabaseTable where id = 1
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor != null)
cursor.moveToFirst();
return new Note(cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4));
}
public List<Note> getNotes() {
SQLiteDatabase db = getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
// Select * from databaseTable
String query = "SELECT * FROM "+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
}
this is my DetailActivity :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
Long id = intent.getLongExtra("ID",0);
NoteDataBase db = new NoteDataBase(this);
Note note = db.getNote(id);
Toast.makeText(this, "Title is "+ note.getTitle(), Toast.LENGTH_SHORT).show();
my error is in lines of both my Intent in DetailActivity and getNote method of NoteDataBase.
By defining the column id of your table as:
INT PRIMARY KEY
it is not defined as AUTOINCREMENT, so in every row that you add to the table, the column id is null, because you don't provide any value for it.
The value that is returned by the method addNote(), when you insert a new row, is the value of the column rowid and not the column id.
You must define the column as:
INTEGER PRIMARY KEY
You can also add AUTOINCREMENT in the above definition, if you don't want any deleted ids to be reused.
After you make this change you must uninstall the app from the device, so that the db is deleted and rerun to recreate the db and the table.
Also in the method getNote(), first check with moveToFirst() if the query returned any row:
public Note getNote(long ID){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor.moveToFirst())
return new Note(
cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4)
);
else return null;
}

DataBase access using Loader

I have made a local database.I have accessing it using diffrent methods but i think CursorLoader is the efficient way to access it.But i don't know know how to do it.Can anyone help?Here is my code
Main Activity
public class Main2Activity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
TextView t1;
RecyclerView mRecyclerView;
RecyclerAdapter recyclerAdapter;
RecyclerAdapter adapter;
List<Info> infoList;
String arrr;
int ar;
int Loader_id=1;
private RecyclerView.LayoutManager mLayoutManager;
SimpleCursorAdapter simpleCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final DatabaseHandler db = new DatabaseHandler(this);
List<Info> infos = db.getAllInfo();
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addItemDecoration(new SimpleDivider(Main2Activity.this));
recyclerAdapter = new RecyclerAdapter(this, infos);
mRecyclerView.setAdapter(recyclerAdapter);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
DataBaseHandler
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Dispalymanager";
private static final String TABLE = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
void addInfo(Info info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, info.getName());
values.put(KEY_AGE, info.getAge());
db.insert(TABLE, null, values);
db.close();
}
Info getinfo(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID, KEY_NAME, KEY_AGE}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Info info = new Info(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return info;
}
public List<Info> getAllInfo() {
List<Info> infoList = new ArrayList<Info>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Info contact = new Info();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
infoList.add(contact);
} while (cursor.moveToNext());
}
return infoList;
}
public int updateInfo(Info info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, info.getName());
values.put(KEY_AGE, info.getAge());
return db.update(TABLE, values, KEY_ID + " = ?", new String[]{String.valueOf(info.getID())});
}
public void deleteInfo(Info contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE, KEY_NAME + " = ?", new String[]{String.valueOf(contact.getName())});
db.close();
}
public int getInfoCount() {
String countQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
boolean deleteitem(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE+" where "+KEY_ID+" ="+id);
return true;
}
}

Interchange ids of android database

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

How to get data from database on click of an event?

I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?

Listview with Cusror adapter displays nothing

In my android app, I read some data from SQLite database and tried to display it into listview. Here is my code:
ListView listContent;
SQLiteAdapterno nadapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ofrnumber);
listContent=(ListView)findViewById(R.id.listView1);
nadapter=new SQLiteAdapterno(this);
nadapter.openToRead();
Cursor c=nadapter.queueAll();
String[] from = new String[]{SQLiteAdapterno.KEY_ID, SQLiteAdapterno.KEY_RCODE, SQLiteAdapterno.KEY_RNAME,SQLiteAdapterno.KEY_OFNO};
int[] to = new int[]{R.id.id,R.id.text1,android.R.id.text2,android.R.id.text2};
SimpleCursorAdapter cursorAdapter =new SimpleCursorAdapter(this, R.layout.row,c, from, to);
listContent.setAdapter(cursorAdapter);
}
SQLiteAdapterno:
public class SQLiteAdapterno {
public static final String MYDATABASE_NAME2 = "MY_DATABASEOFRN";
public static final String MYDATABASE_TABLE2 = "MY_OFFERNO";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_RCODE = "rcode";
public static final String KEY_OFNO = "ofno";
public static final String KEY_RNAME = "rname";
public static final String KEY_ID = "_id";
private static final String SCRIPT_CREATE_DATABASE1 =
"create table " + MYDATABASE_TABLE2 + " ("
+ KEY_ID +" integer primary key autoincrement, "
+ KEY_RCODE + " text, "
+ KEY_RNAME + " text, "
+ KEY_OFNO + " text);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapterno(Context c)
{
context=c;
}
public SQLiteAdapterno openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME2, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapterno openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME2, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String rcode, String rname, String ofno){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_RCODE, rcode);
contentValues.put(KEY_RNAME, rname);
contentValues.put(KEY_OFNO, ofno);
return sqLiteDatabase.insert(MYDATABASE_TABLE2, null, contentValues);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_RCODE, KEY_RNAME, KEY_OFNO};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE2, columns,
null, null, null, null, null);
return cursor;
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE2, null, null);
}
I didn't found the result, It doesn't show any items in Listview. Can someone say what is the mistake in this code and how to solve it?
Code seems good. Most likely your Cursor is empty. Try to add simple condition:
Cursor c = nadapter.queueAll();
if (c != null && c.getCount() > 0) {
// set Adapter
}
else {
Toast.makeText(this, "Cursor is empty", Toast.LENGTH_SHORT).show();
}
If Toast will be shown, your getAll() method returns no data.
public Cursor queueAll(){
String[] columns = new String[] {KEY_ID, KEY_RCODE, KEY_RNAME, KEY_OFNO};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE2, columns,
null, null, null, null, null);
return cursor;
}
Here is problem.

Categories

Resources