When I add data into sqlite and open it for the first time, the data inside will be displayed. However, if I try opening it again nothing will show up even though there is data inside. May I know what is the problem?
Class that performs the activity:
public class Watchlist extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHandler.TABLE_ITEM;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from sqlite");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DatabaseHandler db = new DatabaseHandler(this.getApplicationContext());
newDB = db.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " + tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String price = c.getString(c.getColumnIndex("price"));
String date = c.getString(c.getColumnIndex("created_at"));
Log.d("pid",pid);
results.add("Name: " + name + "\n Price: " + price + "\n Date posted: " + date);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
Database handler:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// table name
public static final String TABLE_ITEM = "item";
// Item Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PRICE = "price";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_ITEM + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement,"
+ KEY_NAME + " TEXT, "
+ KEY_PRICE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_ITEM_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_ITEM);
// Create tables again
onCreate(db);
}
/**
* Storing item details in database
* */
public void addItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName()); // item name
values.put(KEY_PRICE, item.getPrice()); // item price
values.put(KEY_CREATED_AT, item.getDate()); // Created At
// Inserting Row
db.insert(TABLE_ITEM, null, values);
db.close(); // Closing database connection
}
/**
* Getting item data from database
* */
public List<Items> getAllItems(){
List<Items> itemList = new ArrayList<Items>();
String selectQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
if (cursor.moveToFirst()) {
do {
Items item = new Items();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDate(cursor.getString(2));
// Adding item to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
/**
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
// Updating item
public int updateItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName());
values.put(KEY_PRICE, item.getPrice());
values.put(KEY_CREATED_AT, item.getDate());
// updating row
return db.update(TABLE_ITEM, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting item
public void deleteItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEM, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
}
Well, don't you delete all the records before closing the database?
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
That would explain that behaviour.
Related
I wrote some codes using this example to save and update 2 long values in SQlite. I can create new row however I can't update it. I try everything which I can but I couldn't update a row and there is no error just not update row. I am using this code to update a row:
db.updateContact(new Contact(consumed, total));
which both consumed and total are long values. I can't see any error however still I couldn't success to update a row. My constructor and databesehandler codes are below:
Contaxt.java
public class Contact {
// private variables
int _id;
double _name;
double _phone_number;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int id, double name, double _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(double name, double _phone_number) {
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int id) {
this._id = id;
}
// getting name
public double getName() {
return this._name;
}
// setting name
public void setName(double name) {
this._name = name;
}
// getting phone number
public double getPhoneNumber() {
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(double phone_number) {
this._phone_number = phone_number;
}
}
DatabeseHandler.java
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 = "name";
private static final String KEY_PH_NO = "phone_number";
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 AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PH_NO + " 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);
}
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// 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_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2));
// 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(cursor.getInt(0));
contact.setName(cursor.getDouble(1));
contact.setPhoneNumber(cursor.getDouble(2));
// 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.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// 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();
}
}
Thanks in advance.
You did not set the id in Contact object.
db.updateContact(new Contact(consumed, total));
In updateContact method : following update query is used :
db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
contact.getID() returns 0, and no id matched with id 0 and nothing updated.
You should pass correct id also
I am getting a "Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference"
public class userDB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserInfo";
// Assignment table name
private static final String TABLE_USERINFO = "user";
// Assignment Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TOKEN = "token";
Context context;
public userDB (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_USERINFO + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TOKEN + " 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_USERINFO);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding user
public void addUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TOKEN, user.getToken());
// Inserting Row
db.insert(TABLE_USERINFO, null, values);
Toast.makeText(context, "Inserted" + values.toString() , Toast.LENGTH_LONG).show();
db.close(); // Closing database connection
}
// Getting All Users
public List<authToken> getAllUsers() {
List<authToken> userList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_USERINFO;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
authToken user = new authToken();
user.setToken(cursor.getString(1));
// Adding user to list
userList.add(user);
} while (cursor.moveToNext());
}
// return user list
return userList;
}
// Update User
public int updateUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TOKEN, user.getToken());
// updating row
return db.update(TABLE_USERINFO, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser().getId())});
}
// Delete user
public void deleteUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_USERINFO, KEY_ID + " = ?",
new String[] { String.valueOf(user.getToken()) });
db.close();
}
// Getting User Count
public int getUserCount() {
String countQuery = "SELECT * FROM " + TABLE_USERINFO;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
I am reading the info in like this: (and userinfo.getToken) is spitting out the token, its something with the sql not adding in db properly.
userDB db = new userDB(getApplicationContext());
dbs = db.getWritableDatabase();
//db.onUpgrade(dbs, 1, 1);
// Inserting Contacts
Log.d("Insert: ", "Inserting .." +
userInfo.getToken());
db.addUser(new authToken(userInfo.getToken()));
// Reading all
Log.d("Reading: ", "Reading all contacts..");
List<authToken> contacts = db.getAllUsers();
for (authToken cn : contacts) {
String log = "Token: " + cn.getToken();
// Writing Contacts to log
Log.d("Name: ", log);
}
Where are you setting context? I think the problem is with the toast message.
You should set context in your constructor method:
Context context;
public userDB (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
This may not be related but in the method getUserCount(), cursor.getCount() should be called before cursor.close().
I'm implementing a "add to favorite" function. Where the user should be able to add data to a database.
The DatabaseHandler is working and I've created a class to handle get/set methods.
I can easily add data to the database, but I can't quite figure out how to check if a specific id is already present and thereby not adding a duplicate to the database.
Here's my DatabaseHandler:
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 = "favoriteMovies";
// DataFavorites table name
private static final String TABLE_NAME = "movies";
// DataFavorites Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_URL = "url";
private static final String KEY_RELEASEDATE = "releaseDate";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DATAFAVORITES_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_URL + " TEXT,"+ KEY_RELEASEDATE + " TEXT" + ")";
db.execSQL(CREATE_DATAFAVORITES_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_NAME);
// Create tables again
onCreate(db);
}
// Adding new movie
public void addMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, movie.getId()); // movie id
values.put(KEY_TITLE, movie.getTitle()); // movie title
values.put(KEY_URL, movie.getUrl()); // movie url (poster)
values.put(KEY_RELEASEDATE, movie.getReleaseDate()); // movie url (poster)
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
// Getting single movie
public DataFavorites getMovie(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID,
KEY_TITLE, KEY_URL, KEY_RELEASEDATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
DataFavorites movie = new DataFavorites(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return movie
return movie;
}
// Getting All movie
public List<DataFavorites> getAllMovie() {
List<DataFavorites> movieList = new ArrayList<DataFavorites>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DataFavorites dataFavorites = new DataFavorites();
dataFavorites.setId(Integer.parseInt(cursor.getString(0)));
dataFavorites.setTitle(cursor.getString(1));
dataFavorites.setUrl(cursor.getString(2));
dataFavorites.setReleaseDate(cursor.getString(3));
// Adding movie to list
movieList.add(dataFavorites);
} while (cursor.moveToNext());
}
// return movie list
return movieList;
}
// Getting movie Count
public int getMoviesCount(){
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single movie
public int updateMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, movie.getId());
values.put(KEY_TITLE, movie.getTitle());
values.put(KEY_URL, movie.getUrl());
values.put(KEY_RELEASEDATE, movie.getReleaseDate());
// updating row
return db.update(TABLE_NAME, values, KEY_ID + " = ?",
new String[] { String.valueOf(movie.getId()) });
}
// Deleting single movie
public void deleteMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(movie.getId()) });
db.close();
}
And here I want to add data if id doesn't already exist:
public void AddToFavorites(MenuItem item) {
DatabaseHandler db = new DatabaseHandler(this);
/* if ( id is not there ){
// Inserting movie
Log.d("Insert: ", "Inserting movie..");
db.addMovie(new DataFavorites(Integer.parseInt(Id), Title, Poster, Release));
} */
}
Add a UNIQUE index to the Table column to prevent duplicate entries. Also note that it will throw an Exception if duplicate is inserted, so don't forget to handle that
you should use :
db.execSql("INSERT OR IGNORE INTO movies (columns names) VALUES (your values)");
or
db.execSql("INSERT OR REPLACE INTO movies (columns names) VALUES (your values)");
to insert the values, if they are already in the table they will not be added(first method) or they will be replaced(second method).
Heyhey :)
I looked at several Questions to the same topic, but I found no solution to my problem.
A NullPointerException at this.getReadableDatabase(); appears...
Here's my Code:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "TODO_APP";
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create table ITEMS
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
this.onCreate(db);
}
public void addItem(DB_Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
public DB_Item getItem(String name) {
//!!!!! Here is one problem !!!!!
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
//!!!!!!!!!! here is the other Problem
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
[and so on, didn't copy the whole code]
Hope you can help me...
The error appears definitely at SQLiteDatabase db = this.getReadableDatabase();
Output:
09-03 08:34:17.863: E/AndroidRuntime(7074): java.lang.RuntimeException: Unable to start activity ComponentInfo{todo.todo_list/todo.view.StartApp}: java.lang.NullPointerException
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.database.DatabaseHandler.getAllItems(DatabaseHandler.java:144)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.helper.SortItems.sortItemsCategory(SortItems.java:16)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.view.StartApp.onCreate(StartApp.java:36)
chnage you class to something like this:
package com.mhp.example;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "dbname";
private static final int DATABASE_VERSION = 1;
tring CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_ITEMS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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 contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void addItem(DB_Item item) {
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
}
public DB_Item getItem(String name) {
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
Cursor cursor = db.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
NOTE: when you create object from DBAdapter,you should open() db and after your work close() it.
DBAdapter db = new DBAdapter(contex);
db.open();
//do you work
db.close();
Just use getReadableDatabase() without this.
I am trying to pass data from an sqlite table to a username textview in my home fragment class, I am having difficulties displaying the data in the textview.
Here is my DatabaseHelper class where all my table is created:
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 = "u168512214_barzd";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_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_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
Log.i("key_name","value is: " + cursor.getString(1));
Log.i("key_email","value is: " + cursor.getString(2));
Log.i("key_uid","value is: " + cursor.getString(3));
Log.i("key_created_at","value is: " + cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
her is my fragmentHome class where I want to display the username in a textView:
DatabaseHandler db;
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
ArrayList> nameList;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnViewBars = (Button)rootView.findViewById(R.id.btnViewBars);
btnNewBar = (Button)rootView.findViewById(R.id.btnCreateBar);
// return rootView;
db= new DatabaseHandler(getActivity());
HashMap<String, String> user = db.getUserDetails();
for(int i=0; i<user.size();i++) {
username.settext(user.get(i).get("name"));
}