I want built a Android Application with a SQLite Database. I have two Java Classes. The First is the Contact Class ans the second the DatabaseHandle class for the operations how add, update etc...
I don't get a error but if I start my Application I become this message ...
Here is my Contact Class
package de.linde.sqlite;
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){}
public Contact(int id,String name,String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name,String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Here is my DatabaseHandler Class
package de.linde.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
//Datenbank version
private static final int DATABASE_VERSION = 1;
//Datenbankname
private static final String DATABASE_NAME = "contactsManager";
//Tabellenname
private static final String TABLE_CONTACTS = "contacts";
//Tabellenspalten
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);
}
public void onCreate(SQLiteDatabase db){
String CREATE_CONTACTS_TABLE = "CREATE TABLE" + TABLE_CONTACTS + "("
+ KEY_ID + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
public 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 Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public 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(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
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();
}
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()) });
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
}
Here is my MainActivity
package de.linde.sqlite;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Wladimir","024324324"));
db.addContact(new Contact("Max","0324324324"));
db.addContact(new Contact("Benny","0324324"));
db.addContact(new Contact("derSchwarze","051324324"));
Log.d("Reading: ","Reading all Contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
Log.d("Name: ", log);
}
}
}
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
What I make wrong :(
Add spaces between the values that you add to CREATE_CONTACTS_TABLE and the concatenated string, so you build a valid table creation string:
"CREATE TABLE " + TABLE_CONTACTS + " (" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, " + KEY_PH_NO + " TEXT)";
You'll need to uninstall the app from the phone/emulator and then run it again to make the database to be recreated again.
The same thing is valid for the String in the onUpgrade method:
"DROP TABLE IF EXISTS " + TABLE_CONTACTS
Related
I want to use two tables in my SQLite database but when I try to read the second table my app crashes.
I have a table for the items in a storage and another table for the employees of the storage.
Here is my database class:
public class Database extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";
protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;
public Database(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DESCRIPTION + " TEXT, "
+ KEY_CATEGORY + " TEXT, "
+ KEY_ORIGIN + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_BRAND + " TEXT)";
String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
+ KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SURNAME + " TEXT, "
+ KEY_NAME + " TEXT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT)";
db.execSQL(CREATE_ITEMS_TABLE);
db.execSQL(CREATE_DIPENDENTI_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
this.onCreate(db);
}
public void Add(String des, String cat, String pro, String data, String brand) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DESCRIPTION, des);
contentValues.put(KEY_CATEGORY, cat);
contentValues.put(KEY_ORIGIN, pro);
contentValues.put(KEY_DATE, data);
contentValues.put(KEY_BRAND, brand);
sqLiteDatabase.insert(TAB_NAME,null, contentValues);
sqLiteDatabase.close();
}
public void Add(String cog, String nom, String user, String pass) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURNAME, cog);
contentValues.put(KEY_NAME, nom);
contentValues.put(KEY_USERNAME, user);
contentValues.put(KEY_PASSWORD, pass);
sqLiteDatabase.insert(TAB_NAME2,null, contentValues);
sqLiteDatabase.close();
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + ";";
return sqLiteDatabase.rawQuery(query, null);
}
public ArrayList getInfoDip() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
ArrayList<String> al=new ArrayList<>();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
al.add(cursor.getString(cursor.getColumnIndex("surname")));
al.add(cursor.getString(cursor.getColumnIndex("name")));
al.add(cursor.getString(cursor.getColumnIndex("username")));
al.add(cursor.getString(cursor.getColumnIndex("password")));
cursor.moveToNext();
}
return al;
}
public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
SQLiteDatabase db = this.getWritableDatabase();
if(!des.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
if(!cat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!pro.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
if(!dat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!bran.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}
public void Modify(int cod, String cog, String nom, String user, String pass){
SQLiteDatabase db = this.getWritableDatabase();
if(!cog.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!nom.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!user.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!pass.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}
public void Delete(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}
public void DeleteDip(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}
public Cursor Search(int cod){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public Cursor Search(String des){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public void DeleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TAB_NAME);
}
}
and here is the activity where I try to get the ArrayList with the data:
private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
db.Add("admin","admin","admin","admin");
al.addAll(db.getInfoDip());
But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?
Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:
String query = "SELECT * FROM " + TAB_NAME + ";";
Best practice:
String query = String.format("SELECT * FROM %s", TAB_NAME);
So let's get to the getInfoDip method, you should try this:
public List<ContentValues> getInfoDip() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", TAB_NAME2);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContentValues> list = new ArrayList<>(res.getCount());
while (!res.isAfterLast()){
String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
String name = res.getString(res.getColumnIndex(KEY_NAME));
String username = res.getString(res.getColumnIndex(KEY_USERNAME));
String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
list.add(new ContentValues(surname, name, username, password));
res.moveToNext();
}
return list;
}
Here is my whole SQLite test program, check out maybe it helps you:
package com.example.vezba09;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME = "contact_database";
public Database(#Nullable Context context) {
super(context, DATABASE_FILE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format(
"CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID,
ContactModel.COLUMN_CONTACT_NAME,
ContactModel.COLUMN_CONTACT_EMAIL,
ContactModel.COLUMN_CONTACT_PHONE
);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
db.execSQL(query);
onCreate(db);
}
//Dodavanje kontakta
public void addContact(String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.insert(ContactModel.TABLE_NAME, null, cv);
}
//Izmena
public void editContact(int contactId, String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.update(ContactModel.TABLE_NAME,
cv,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public int deleteContact(int contactId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public ContactModel getContactById(int contactId) {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s WHERE %s = ?",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID);
Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
if(res.moveToFirst()) {
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
return new ContactModel(contactId, name, email, phone);
}
else {
return null;
}
}
public List<ContactModel> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContactModel> list = new ArrayList<>(res.getCount());
while(!res.isAfterLast()) {
int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
list.add(new ContactModel(contactId, name, email, phone));
res.moveToNext();
}
return list;
}
}
Try this and feel free to ask more questions :)
Best regards, Sanady
How to read and display "email" and "address" in HomeAcitivity TextView.
The database designed to be store only 1 row of data.
DatabaseHandler.java
package com.example.androidjhfong.library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 = "android_database";
// 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_ADDRESS = "address";
private static final String KEY_PHONE = "phone";
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_ADDRESS + " TEXT,"
+ KEY_PHONE + " 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 address, String phone, 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_ADDRESS, address); // Address
values.put(KEY_PHONE, phone); // phone
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){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("address", cursor.getString(4));
user.put("phone", cursor.getString(5));
user.put("created_at", cursor.getString(6));
}
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;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
/**
* Getting product status
**/
public String getData() {
String username;
String getdata = "SELECT name FROM " + TABLE_LOGIN;
//String[] columns = new String[]{ KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_PHONE};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(getdata, null);
cursor.moveToFirst();
username=cursor.getString(cursor.getColumnIndex("name"));
cursor.close();
db.close();
return username;
}
}
how to display the retrieve the data and display in HomeActivity correctly?
HomeActivity
public class HomeActivity extends Activity implements OnItemSelectedListener{
TextView inputname
TextView inputemail;
TextView inputaddress;
Button btnPurchase;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ADDRESS = "address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Home);
inputname= (TextView) findViewById(R.id.qrpurchaseitem);
inputaddress = (TextView) findViewById(R.id.qrtextpurchaseaddress);
inputemail = (TextView) findViewById(R.id.qrtextpurchasecomment);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> key = db.getUserDetails();
String text= DatabaseHandler.getUserDetails();
}
in your HomeActivty add this both line
String email=db.getEmail()
String address=db.getAddress();
Now then you can use below method in you Database Handler class, just change variable name from below methods
public String getStartBal() {
Cursor cr=ourDatabase.rawQuery("SELECT "+KEY_START_BAL+" FROM "+DB_TABLE,null);
String sum="";
for(cr.moveToFirst();!cr.isAfterLast();cr.moveToNext()){
sum=cr.getString(cr.getColumnIndex(KEY_START_BAL));
}
cr.close();
return sum;
}
I am trying to figure out how to populate my listview with data from a sqlite databse. I actually followed the tutorial posted here
My code is posted below:
DatabaseHandler.java
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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," + 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);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// 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(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(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(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(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();
}
}
Mainactivity.java
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Listview list =(Listview) findviewbyid(R.id.list);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "" + cn.getName() +"";
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
What am I doing wrong?
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.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 9 years ago.
I have another problem again :(
The error I encountered with this one is that it does not create a table named contacts but I have the code to create database and yet it does not create it.How to solve this? Thank you again for answering.
package com.mobilebasedsignlanguage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class alphaconv extends Activity {
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabetview);
DataBaseHandler db = new DataBaseHandler(this);
//get image from drawable..
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.a);
//convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
//Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("A", imageInByte));
//Read all contacts from db
List<Contact> contacts = db.getAllContacts();
for(Contact cn: contacts) {
String log = "ID: " + cn.getID() + "Name: " + cn.getName() + ", Image: " + cn.getImage();
Log.d("Result: ", log);
imageArry.add(cn);
}
adapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry);
ListView dataList = (ListView)findViewById(R.id.list);
dataList.setAdapter(adapter);
}
}
here is the other java classes:
Contact.java
package com.mobilebasedsignlanguage;
public class Contact {
int _id;
String _name;
byte[] _image;
public Contact() {
}
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;
}
public Contact(String contactID, String name, byte[] image) {
this._name = name;
this._image = image;
}
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}
public int getID() {
return this._id;
}
public void setID(int keyId ) {
this._id = keyId;
}
public String getName() {
return this._name;
}
public void setName(String name) {
this._name = name;
}
public byte[] getImage() {
return this._image;
}
public void setImage(byte[] image) {
this._image = image;
}
}
ContactImageAdapter.java
package com.mobilebasedsignlanguage;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
byte[] outImage = picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
DbHandler.java
package com.mobilebasedsignlanguage;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "SLdb";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name);
values.put(KEY_IMAGE, contact._image);
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
Contact getContact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null,null,null,null);
if(cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(1));
return contact;
}
public List<Contact> getAllContacts() {
List<Contact> contactlist = new ArrayList<Contact>();
String selectQuery = "SELECT * FROM contacts ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
contactlist.add(contact);
}while (cursor.moveToNext());
}
db.close();
return contactlist;
}
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] {String.valueOf(contact.getID()) });
db.close();
}
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
the error at the log cat is this:
02-18 11:49:25.938: E/SQLiteLog(6044): (1) no such table: contacts
02-18 11:49:26.078: E/SQLiteDatabase(6044): Error inserting image=[B#40e29b40 name=A
02-18 11:49:26.078: E/SQLiteDatabase(6044): android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: INSERT INTO contacts(image,name) VALUES (?,?)
Do a log or toast in the onCreate method to see if it's called and if yes then delete your old table as this is called only once and if the table already exists it will not be executed again.
Also, please try using the below query, sometimes spaces in the create statement cause the issue.
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + " ("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, "
+ KEY_IMAGE + " BLOB" + ");";
The problem is that you are not overriding the SQLiteOpenHelper onCreate method, so it is not being called.
Try to put override annotation on the onCreate and onUpgrade methods:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}