Related
i try to save current date values when button get clicked....i use DBAdapter for save parameters to sqlite and it was fine when used for 2 fields like example of DBAdapter but when i edited DBAdapter for 6 fields this doesnt work.where is my problem?
DBAdapter.java
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_YEAR = "year";
public static final String KEY_MONTH = "month";
public static final String KEY_DAY = "day";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String KEY_SECOND = "second";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_YEAR, KEY_MONTH, KEY_DAY, KEY_HOUR, KEY_MINUTE, KEY_SECOND};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo12";
public static final String DATABASE_TABLE = "mainToDo12";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_YEAR + " TEXT NOT NULL, "
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
+ KEY_SECOND + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
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 be inserted into the database.
public long insertRow(String year, String month,String day, String hour,String minute,String second) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_YEAR, year);
initialValues.put(KEY_MONTH, month);
initialValues.put(KEY_DAY, day);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
initialValues.put(KEY_SECOND, second);
// Insert the data 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 year, String month,long day, String hour, String minute,long second) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MONTH, month);
newValues.put(KEY_DAY, day);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MINUTE, minute);
newValues.put(KEY_SECOND, second);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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);
}
}
}
MainActivity.java
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button plus;
int second,minute,houre,day,mounth,year;
DBAdapter mDb = new DBAdapter(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ViewGroup.LayoutParams superparams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout table = new LinearLayout(this);
plus = new Button(this);
plus.setText("+");
table.addView(plus);
setContentView(table);
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Calendar c = Calendar.getInstance();
second = c.get(Calendar.SECOND);
minute = c.get(Calendar.MINUTE);
houre = c.get(Calendar.HOUR);
day = c.get(Calendar.DAY_OF_MONTH);
mounth = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
mDb.open();
mDb.insertRow(Integer.toString(year), Integer.toString (mounth),Integer.toString(day), Integer.toString(houre),Integer.toString(minute), Integer.toString(second));
mDb.close();
mDb.open();
Cursor g=mDb.getRow(2);
DisplayContact(g);
mDb.close();
}
});
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,"id: "+c.getString(0)+"\n"+
"year: "+c.getString(1)+"\n"+
"month: "+c.getString(2),
Toast.LENGTH_LONG).show();
}
}
You're missing commas , between your column specifications here:
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
After adding the missing commas, either uninstall your app or increment the schema version to get the table recreated.
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);
}
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
I was trying to add the data i receive from some specific messages to SQLite database..
But when i run my application i am getting error which says ... Fatal Exception : Main caused by Java Null Pointer exception at the InsertTitle Function in my DBAdapter.java
This is my DBAdapter Class
package com.lalsoft.janko;
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
{
public static final String KEY_ROWID = "_id";
public static final String KEY_GQTY = "gqty";
public static final String KEY_NQTY = "nqty";
public static final String KEY_DATE = "ddate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "lalaqua";
private static final String DATABASE_TABLE = "nsales";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "gqty text not null, nqty text not null, "
+ "ddate text not null);";
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)
{
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 titles");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(String gqty, String nqty, String ddate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GQTY, gqty);
initialValues.put(KEY_NQTY, nqty);
initialValues.put(KEY_DATE, ddate);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_GQTY,
KEY_NQTY,
KEY_DATE},
null,
null,
null,
null,
null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_GQTY,
KEY_NQTY,
KEY_DATE
},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String gqtr,
String nqty, String ddate)
{
ContentValues args = new ContentValues();
args.put(KEY_GQTY, gqtr);
args.put(KEY_NQTY, nqty);
args.put(KEY_DATE, ddate);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
This is the class which extends from BroadcastReceiver, which is calling the inserttitle function..
package com.lalsoft.janko;
import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
public class SMSReceiver extends BroadcastReceiver
{
public String SendMsgBody;
private static final String LOG_TAG = "JankoSMS";
public DBAdapter db;
public Integer isDone=0;
public Double GrossQty,NetQty;
#Override
public void onReceive(Context context, Intent intent)
{
db = new DBAdapter(context);
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String PhNo;
String MsgBody;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
PhNo=msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
MsgBody=msgs[i].getMessageBody().toString();
str += "\n";
// EncodeSMS(MsgBody);
String GQtyS,NQtyS,sDate;
GQtyS="Ok";
NQtyS="Done";
sDate=getDate();
Log.i(LOG_TAG, "Date" +" "+ sDate +" "+ GQtyS +" "+ NQtyS);
long id;
id = db.insertTitle(GQtyS ,NQtyS,sDate);
}
}
}
public static String getDate()
{
Calendar c = Calendar.getInstance();
String sDate = c.get(Calendar.DAY_OF_MONTH) + "-"
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.YEAR);
//+ " at " + c.get(Calendar.HOUR_OF_DAY)
//+ ":" + c.get(Calendar.MINUTE);
return sDate;
}
}
Also i have checked the database is not getting created..
So what should be the possible cause of this issue and how can i solve this?? Please help me out of this trouble.
The problem is in line db.insert() of insertTitle() method. You have to assign the value of db before using so use open the database before using by calling open() as first statement inside insertTitle() method
Your code will be something like the below
public long insertTitle(String gqty, String nqty, String ddate)
{
open();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GQTY, gqty);
initialValues.put(KEY_NQTY, nqty);
initialValues.put(KEY_DATE, ddate);
return db.insert(DATABASE_TABLE, null, initialValues);
}
I guess you haven't called db.open(); that is this method
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
Follow the above 2 suggestions given by sunil & lalit
include the below one also i.e place db.execSQL(DATABASE_CREATE); in try catch block
public void onCreate(SQLiteDatabase db) {
System.out.println("table created....");
try{
db.execSQL(DATABASE_CREATE);
}catch (Exception e) {
// TODO: handle exception
}
}