Listview with Cusror adapter displays nothing - java

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.

Related

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

Populating listview from Database, doesn't show anything

I saw this tutorial: https://www.youtube.com/watch?v=gaOsl2TtMHs
but it seem that when i see the activity there isn't any item listview :\
What can be the problem? I put my code under below
The Main Activity.java
public class Prova2 extends Activity {
int[] imageIDs = {
R.drawable.spaghettiscoglio,
R.drawable.abbacchioascottadito,
R.drawable.agnellocacioeova,
R.drawable.agnolotti,
R.drawable.alettedipollo,
R.drawable.amaretti,
R.drawable.anatraarancia,
R.drawable.alberinatale
};
int nextImageIndex = 0;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova2);
openDB();
populateListViewFromDB();
registerListClickCallback();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_AddRecord(View v) {
int imageId = imageIDs[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % imageIDs.length;
// Add it to the DB and re-draw the ListView
myDb.insertRow("Jenny" + nextImageIndex, imageId, "Green");
populateListViewFromDB();
}
public void onClick_ClearAll(View v) {
myDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.tvFruitPrice, R.id.ivFruit, R.id.tvFruitPrice, R.id.smalltext};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.sis, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
String message = "ID: " + idDB + "\n"
+ "Name: " + name + "\n"
+ "Std#: " + studentNum + "\n"
+ "FavColour: " + favColour;
Toast.makeText(Prova2.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
The DBAdaptor.java
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, int studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}

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

problem in database in android

hi i am an SEO and i am in currently practicing android development of my own. i studied about database storing in android developers site and found an example code that to be in a notepad.
I tried using it in my project. In my project i have placed 2 edit boxes with a OK button, when the OK button is clicked the data in the edit box gets stored and it is shown in a new page.
the following is the code of my project's main class file,
{
b = (Button)findViewById(R.id.widget30);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_ET1);
String body = extras.getString(NotesDbAdapter.KEY_ET2);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
et1.setText(title);
}
if (body != null) {
et2.setText(body);
}
}
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(et1.getText().toString().length() == 0 && et2.getText().toString().length() == 0)
{
et.setVisibility(View.VISIBLE);
alertbox();
}
else
{
main.this.finish();
Intent myIntent = new Intent(v.getContext(), T.class);
startActivityForResult(myIntent, 0);
}
}
});
}
public void alertbox()
{
et = new TextView(this);
Builder alert =new AlertDialog.Builder(main.this);
alert.setTitle("Alert");
alert.setMessage("Required all fields");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
});
AlertDialog alert1 = alert.create();
alert1.show();
}
}
the following is the code of the DataBaseAdapter
public class NotesDbAdapter {
public static final String KEY_ET1 = "a";
public static final String KEY_ET2 = "b";
public static final String KEY_ROWID = "_id";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String a, String b) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ET1, a);
initialValues.put(KEY_ET2, b);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ET1,
KEY_ET2}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ET1, KEY_ET2}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String a, String b) {
ContentValues args = new ContentValues();
args.put(KEY_ET1, a);
args.put(KEY_ET2, b);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
when i run the project the new page is opening but the data's entered is not shown there.
what is to be the error. pls teach me
You are going to need to get an instance of your database adapter
NotesDbAdapter adapter = new NotesDbAdapter(this); //pass activity context as a param
then you need to use the open method of the new database object to open the database
adapter.open();
now call the store method
String str = myEditText.getText().toString();
String str1 = "random other string";
adapter.createNote(str, str1);
I notice that your createNote method takes two params. I dont know where you want to get the other data from, so I just used 'random other string'. Sub in the data you want to store as appropriate.
Finally you will need to close the database:
adapter.close();
And you have successfully stored the information. See this for help on how to use the console to view the data that you have entered into the database. (See specifically the sqlite3 portion of the page) Alternatively you could write some code to display it on the screen after retrieving it. You are going to need to read about cursors if you want to retrieve info. See here for some information on that.

Categories

Resources