Add images to a database for q quiz app - java

I'm developping and android quizz app and i have two problems.
First i cannot update the questions and second i want to store images in the database with the questions.This my database code
Is there someone who can help me?
Thanks
package com.example.toureamidou.piste;
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;
import java.util.ArrayList;
import java.util.List;
/**
* Created by TOURE Amidou on 24/02/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Question";
private static final String TABLE_QUEST = "quest";
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer";
private static final String KEY_OPTA= "opta";
private static final String KEY_OPTB= "optb";
private static final String KEY_OPTC= "optc";
private SQLiteDatabase dbase;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase=db;
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
db.execSQL(sql);
addQuestions();
}
private void addQuestions() {
Questions q1=new Questions("FFFFF","Tata", "Titi", "Toto", "Tata");
this.addQuestion(q1);
Questions q2=new Questions("Quel est le plus grand pays au monde", "Suisse", "Italie", "Chine", "Chine");
this.addQuestion(q2);
Questions q3=new Questions("Comment s'appele le président francais","Obama", "Hollande","Gorbatchev", "Hollande" );
this.addQuestion(q3);
Questions q4=new Questions("zzzzzzzzzzzzzzzzzzzz", "ali", "dede", "home","dede");
this.addQuestion(q4);
Questions q5=new Questions("Quel est l'homme le plus riche au monde","Gates","Trump","Carlos Slim","Trump");
this.addQuestion(q5);
}
private void addQuestion(Questions quest) {
Log.d("addQuestions", quest.toString());
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
dbase.insert(TABLE_QUEST, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
onCreate(db);
}
public List<Questions> getAllQuestions() {
List<Questions> quesList = new ArrayList<Questions>();
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Questions quest = new Questions();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
return quesList;
}
public int updateQuestions (Questions questions){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("questions",questions.getQUESTION());
contentValues.put("answer",questions.getANSWER());
contentValues.put("opta",questions.getOPTA());
contentValues.put("optb",questions.getOPTB());
contentValues.put("optc",questions.getOPTC());
int i = db.update(TABLE_QUEST, contentValues, KEY_ID + " = ?", new String[]{String.valueOf(questions.getID())});
db.close();
return i;
}
}

Another way You can also image load with asset folder
//load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex)
{
ex.printStackTrace();
}

in order for database records to "stick" you need to be in a Transaction.
db.getWritableDatabase();
db.beginTransaction();
...INSERT, UPDATE, DELETE
if (ok) {
db.setTransactionSuccessful();
}
db.endTransaction();
db.close();
images could be stored in a BLOB column.

Use this to get you image as String and save it
public String getStringImage() {
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} else {
return null;
}
}

change image into byte{}
Bitmap b=BitmapFactory.decodeResource(getResources(),R.drawable.androidpics);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
img=bos.toByteArray();
insert image into database
................................................
db=h.getWritableDatabase();
btninsert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv=new ContentValues();
cv.put("image", img);
db.insert("tableimage", null, cv);
System.out.println("image insert successfully...............................");
}
}
);

Related

Android Save And Get Image From Sqlite Database

Dears
How I can Android Save Image And Get Image From Sqlite Database I'm Using Android Studio ?
Might be too late. but useful for future readers..
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.util.HashMap;
/**
* Created by Noorul on 23-05-2016.
*/
#SuppressWarnings("ALL")
public class DBSplash extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "SplashDB.db";
public static final String SPLASH_TABLE_NAME = "splash_db";
private HashMap hp;
public DBSplash(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"create table " + SPLASH_TABLE_NAME + "( name TEXT, image BLOB)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertImage(String name, Bitmap img) {
Bitmap storedBitmap = null;
String sql = "INSERT INTO " + SPLASH_TABLE_NAME + " (name,image) VALUES(?,?)";
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement insertStmt = db.compileStatement(sql);
byte[] imgByte = getBitmapAsByteArray(img);
try {
storedBitmap = getImage(name);
} catch (Exception e) {
AppLog.exception(e);
}
if (storedBitmap == null) {
insertStmt.bindString(1, name);
insertStmt.bindBlob(2, imgByte);
insertStmt.executeInsert();
db.close();
}
return true;
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, SPLASH_TABLE_NAME);
return numRows;
}
public Bitmap getImage(String name) {
String qu = "SELECT * FROM " + SPLASH_TABLE_NAME;
Cursor cur = null;
SQLiteDatabase db = this.getReadableDatabase();
try {
cur = db.rawQuery(qu, new String[]{});
} catch (Exception e) {
AppLog.exception(e);
}
if (cur != null) {
if (cur.moveToFirst()) {
int index = cur.getColumnIndexOrThrow("image");
byte[] imgByte = cur.getBlob(index);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
return null;
}
public byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, outputStream);
return outputStream.toByteArray();
}
}
Use this code. But storing images in databases is not not best practices.change the image size if you need unblurred image. IMages are blob type with high memory . mobile is smaller device . so storing many images in sqlite db means, it will be ugly. so use #thuongle method
You can check this tutorial for implementing Sqlite in Android.
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Instead working with Contact for example, you can implement this way
public class Image{
String imagePath; //it is your absolute image file path
}
And your DatabaseHandler can be implemented like below
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 = "imagedb";
// Contacts table name
private static final String TABLE_IMAGE = "images";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE_PATH = "name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String sqlQuery = "CREATE TABLE " + TABLE_IMAGE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE_PATH + " TEXT)";
db.execSQL(sqlQuery);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGE);
// Create tables again
onCreate(db);
}
// Adding new image
public void addImage(Image image) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE_PATH, image.imagePath); // Image path
// Inserting Row
db.insert(TABLE_IMAGE, null, values);
db.close(); // Closing database connection
}
// Getting single image
public Image getImage(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_IMAGE, new String[] { KEY_ID,
KEY_IMAGE_PATH}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Image image = new Image(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return image
return image;
}
}

Showing strings from a SQL file in java

I have a SQL file with some data that I want to show in my app, the data will be shown in a list view.
I want to include the SQL file in the apk.
I have three questions:
Is including the SQL file with the apk is the best option or is there a better one?
If putting it in the apk is the best option, where do I put it?
How do I get the strings from the file and show them in the app?
Thanks for the help!
So am really sure what you truly need is an SQLite in android :
Now if that is so, then what you need is to create an adapter class as seen below :
package extension.yourappname.whatever;
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
//public static final String DATABASE_NAME = "my_db";
//public static final String DATABASE_TABLE = "contacts";
//public static final int DATABASE_VERSION = 1;
public static final String START_TBL_CREATION = "create table "+Appiah.DATABASE_TABLE+" (_id integer primary key autoincrement, ";
public static final String [] TABLE_COLUMNS_TO_BE_CREATED = new String []{
KEY_NAME+" text not null, ",
KEY_EMAIL+" text not null"
};
public static final String END_TBL_CREATION = ");";
private static final String DATABASE_CREATE = START_TBL_CREATION
+ TABLE_COLUMNS_TO_BE_CREATED[0]
+ TABLE_COLUMNS_TO_BE_CREATED[1]
+ END_TBL_CREATION;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);//there would be an error initially but just keep going...
}
private static class DatabaseHelper extends SQLiteOpenHelper{//after importing for "SQLiteOpenHelper", Add unimplemented methods
DatabaseHelper(Context context){
super (context, Appiah.DATABASE_NAME, null, Appiah.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
}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 SQLiteException{
db = DBHelper.getWritableDatabase();
return this;
}
//closes the database
public void close(){
DBHelper.close();
}
//insert a contact into the database
public long insertContact(String name, String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(Appiah.DATABASE_TABLE, null, initialValues);
}
//deletes a particular contact
public boolean deleteContact(long rowId){
String whereClause = KEY_ROWID + "=" + rowId;
String[] whereArgs = null;
return db.delete(Appiah.DATABASE_TABLE, whereClause, whereArgs) > 0;
}
//retrieves all the contacts
public Cursor getAllContacts(){
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
return db.query(Appiah.DATABASE_TABLE, columns, selection, selectionArgs, groupBy, having, orderBy);
}
//retrieve a particular contact with ID as input
public Cursor getContact_with_ID(long rowId) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_ROWID + "=" + rowId;
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact_with_nameEntered(String name_str) throws SQLException {
boolean distinct = true;
String table = Appiah.DATABASE_TABLE;
String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
String selection = KEY_NAME + "=" + name_str;//check again and do "%" thing to expand scope and increase chances of a name getting found or populated
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//update a contact
public boolean updateContact(long rowId, String name, String email){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
String table = Appiah.DATABASE_TABLE;
ContentValues values = args;
String whereClause = KEY_ROWID + "=" + rowId;
String []whereArgs = null;
return db.update(table, values, whereClause, whereArgs) > 0;
}
/*
TO USE ANY OF THE ABOVE METHODS :
1. type this before in your "onCreate()" : DBAdapter db = new DBAdapter(this);
2. in the special case of getting all contacts to display : do the ff :
db.open();
Cursor c = db.getAllContacts();
if(c.moveToFirst()){
do{
textView.setText("ID : " + c.getString(0) + "\nName : " + c.getString(1) + "\nEmail Address : " + c.getString(2) );
}while(c.moveToNext());//the "while" added ensures that, the looping process occurs
}
db.close();
*/
}

android getWritableDatabase

package ru.phonebook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
// Класс для работы БД
public class DatabaseHandler extends SQLiteOpenHelper
{
// Версия базы данных
private static final int _DatabaseVersion = 3;
// Название базы
private static final String _DatabaseName = "ContaсtDatabase";
// Таблица
private static final String _TableName = "subscribers";
// Поля в таблице
private static final String _Field_ID = "id_subscribers";
private static final String _Field_Name = "name_subscribers";
private static final String _Field_Phone = "phone_subscribers";
// Запрос создания таблицы
private static final String _Query_CreateTable = "CREATE TABLE " + _TableName + "("
+ _Field_ID + " INTEGER PRIMARY KEY,"
+ _Field_Name + " TEXT,"
+ _Field_Phone + " TEXT);";
// Запрос вывода всех контактов
private static final String _Query_SelectTable = "SELECT * FROM " + _TableName;
// Запрос на вывода количества контактов
private static final String _Query_CountRows_Table = "SELECT COUNT(*) FROM " + _TableName;
// Конструктор
public DatabaseHandler(Context context)
{
super(context, _DatabaseName, null, _DatabaseVersion);
Log.e("n", "Call constructor");
}
// Добавление абонента в базу данных
public void AddSubcriber(Subscriber contact)
{
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues values = new ContentValues();
values.put(_Field_Name, contact.getName());
values.put(_Field_Phone, contact.getPhone());
db.insert(_TableName, null, values);
db.close();
*/
Log.d("n", "Insert rows: " + contact.getName());
}
// Вывод всех абонентов
public List<Subscriber> getAllSubscriber()
{
List<Subscriber> allSubscriber = new ArrayList<Subscriber>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(_Query_SelectTable, null);
if(cursor.getCount() != 0)
{
do
{
Subscriber tmpSub = new Subscriber(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
allSubscriber.add(tmpSub);
} while(cursor.moveToNext());
}
cursor.close();
db.close();
return allSubscriber;
}
// Вывод количества абонентов
public int getSubscriberCount()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(_Query_CountRows_Table, null);
db.close();
cursor.close();
return cursor.getCount();
}
// Удаление всех контактов
public void deleteAllSubscriber()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(_TableName, null, null);
db.close();
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(_Query_CreateTable);
Log.e("n", "Database create");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + _TableName);
onCreate(db);
Log.e("n", "Database onUpgrade");
}
}
This is my class for communicate with database, and after in main programm i add new rows:
DatabaseHandler dbConnect = new DatabaseHandler(this);
dbConnect.AddSubcriber(new Subscriber("Petr Umine", "19234234432"));
In my logCat i view error:
"02-24 19:12:41.440 17415-17415/ru.phonebook W/System.err﹕ Invalid int: "" "
i am debuging method "AddSubcriber", and this error crush after this line SQLiteDatabase db = this.getWritableDatabase();
what is it?

NullPointerException at this.getReadableDatabase();

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.

android SQLite database.. no such table: [duplicate]

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

Categories