I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
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;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.
Related
I'm developing an app which is used for contacts and for this i used sqlite database to store name and number so i want to filter name and number for searching for which
i tried that query but
it's not working for me
any solution for problem i used like and "=" both?
public boolean onQueryTextChange(String newText) {
try {
final String temp = newText.toLowerCase();
final ArrayList<Map> map1 = new ArrayList();
try {
dbhelper =new FeedReaderDbHelper(getActivity());
SQLiteDatabase db=dbhelper.getReadableDatabase();
String projection[]={FeedReaderContract.FeedEntry.COLUMNS_TITLE,FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE};
Cursor cursor =db.query(FeedReaderContract.FeedEntry.TABLE_NAME,projection ,FeedReaderContract.FeedEntry.COLUMNS_TITLE+"= ?",new String[]{newText},null,null,null);
while(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMNS_TITLE));
String number = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE));
Map<String, Object> map = new HashMap();
map.put(name, number);
if (name.toLowerCase().contains(temp)) {
map1.add(map);
Phone.this.adapter.Filter(map1);
}
} }
catch(Exception e){
System.out.print(Retriving_list);
}
}catch(Exception e){
Toast.makeText(getActivity(), First_Retrive_Data, Toast.LENGTH_SHORT).show();
}
//DbHelperClass
public class FeedReaderDbHelper extends SQLiteOpenHelper{
public static final int DB_VERSION =1;
public static String getDataBASE_NAME() {
return DataBASE_NAME;
}
public static void setDataBASE_NAME(String dataBASE_NAME) {
DataBASE_NAME = dataBASE_NAME;
}
public static String DataBASE_NAME;
Context context;
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + "(" +
FeedReaderContract.FeedEntry._ID + "INTEGER PRIMARY KEY," +
FeedReaderContract.FeedEntry.COLUMNS_TITLE + " TEXT ," +
FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " TEXT UNIQUE)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, FeedReaderDbHelper.getDataBASE_NAME(), null, DB_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
void addContactValues(FeedReaderDbHelper dbhelper ,String name ,String number){
SQLiteDatabase db= dbhelper.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMNS_TITLE ,name);
values.put(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE,number);
long rows= db.insertWithOnConflict(FeedReaderContract.FeedEntry.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_IGNORE);
if (rows==-1){
// Toast.makeText(context, String.valueOf(rows)+"not interested", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, String.valueOf(rows)+"inserted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
}
It's not clear what exact do you want, but if you want do get only rows with given values, it should looks like this:
String mSearchString = "what do you want to search";
String selection = setupSelectionString();
cursor = database.query(NoteContract.NoteEntry.NOTES_TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
private String setupSelectionString() {
String selection = null;
if (mSearchString != null) {
selection = FeedReaderContract.FeedEntry.COLUMNS_TITLE + " LIKE '%"
+ mSearchString + "%'"
+ " OR " + FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " LIKE '%"
+ mSearchString + "%'";
}
return selection;
It works in my app
I've founde already a few answers to this topic (for example this), but it is not working. I only get the warning, that it cannot resolve the method 'openOrCreateDatabase(java.lang.String, int, null)'.
Here is my sourcecode:
public class DBHandler
{
SQLiteDatabase database;
DBHandler()
{
database = openOrCreateDatabase("DatabaseName", Context.MODE_PRIVATE, null);
}
}
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
Please check below links
Android SQLite Database Tutorial
SQLite Database Tutorial
SQLite and Android
Structure
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
}
As the commenter has given you the example, you will need to create a subclass of SQLiteOpenHelper class and override the onCreate and onUpgrade methods which will create your database and tables. Then you can use the method getReadableDatabase( ) or getWritableDatabase() of this helper class to get copy of a SQLite database. You can execute the queries on this object.
The code snippet below demonstrates it.
public class DBAdapter {
private SQLiteDatabase database;
private Context context;
private DatabaseHelper dbHelper;
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLES_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+TABLE_QUERY);
}
}
public DBAdapter(Context ctx) {
this.context = ctx;
}
public DBAdapter open() throws SQLException {
dbHelper = new DatabaseHelper(context, DBNAME, null,DBVERSION);
database = dbHelper.getWritableDatabase();
return this;
}
public Cursor executeQuery() {
Cursor result = database.rawQuery(YOUR_QUERY, null);
return result;
}
}
Use SQLite Open Helper developers guide for more help.
public class Sqlhelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "firstname";
Sqlhelper DB = null;
private static final String DATABASE_NAME = "dbname.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "db";
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"firstname TEXT NOT NULL);";
public Sqlhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_TABLE_CREATE);
Log.d("DATABASE", "Table Was Created");
}catch(Exception e){
e.printStackTrace();
}
}
public void open() {
getWritableDatabase();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
Log.d("DATABASE", "Table Was UPDATED");
}
Create "database" name package and include it
Create SQLitHelper name class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLitHelper extends SQLiteOpenHelper {
public static final String DataBase_Name = "ABC";
public static final int Version = 1;
public static final String TblUser = "TblUser";
public static final String TblClassList = "TblClassList";
public static final String TblStudentList = "TblStudentList";
public SQLitHelper(Context context) {
super(context, DataBase_Name, null, Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TblUser +
"(id INTEGER PRIMARY KEY," +
"uid INTEGER," +
"fname TEXT," +
"lname TEXT," +
"email TEXT," +
"password TEXT," +
"teacher TEXT," +
"student TEXT," +
"parent TEXT," +
"status TEXT," +
"landing_page TEXT," +
"createdate TEXT," +
"birthdate TEXT," +
"profilepic TEXT," +
"phone TEXT," +
"address TEXT," +
"gender TEXT," +
"age TEXT," +
"googleid TEXT," +
"facebookid TEXT," +
"alert_time TEXT," +
"sch_name TEXT,"+
"login_with TEXT,"+
"default_zone TEXT)");
db.execSQL("Create table " + TblClassList +
"(id INTEGER PRIMARY KEY," +
"cid INTEGER," +
"uid INTEGER," +
"title TEXT," +
"color TEXT," +
"startdate TEXT," +
"enddate TEXT," +
"qrcode TEXT," +
"createdate TEXT," +
"not_submitted_count TEXT," +
"status TEXT," +
"extra1 TEXT," +
"extra2 TEXT)");
db.execSQL("Create table " + TblStudentList +
"(id INTEGER PRIMARY KEY," +
"uid INTEGER," +
"cid INTEGER," +
"fname TEXT," +
"lname TEXT," +
"email TEXT," +
"profilepic TEXT," +
"student_name TEXT," +
"isleader TEXT," +
"add_homework TEXT," +
"track_submission TEXT," +
"status TEXT," +
"edit_homework TEXT," +
"del_homework TEXT," +
"last_access TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Create DataHelper class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DataHelper {
SQLitHelper sqLitHelper;
SQLiteDatabase sqLiteDatabase;
Context context;
final String TAG = "DataHelper";
public DataHelper(Context context) {
sqLitHelper = new SQLitHelper(context);
this.context = context;
sqLiteDatabase = sqLitHelper.getWritableDatabase();
}
public void open() {
try {
sqLiteDatabase = sqLitHelper.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
sqLiteDatabase.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertUser(HashMap<String, String> list) {
ContentValues values = new ContentValues();
open();
try {
for (String str : list.keySet())
values.put(str, list.get(str));
long rowId = sqLiteDatabase.insert(SQLitHelper.TblUser, null, values);
} catch (Exception e) {
Log.e(TAG, "insertUser " + e.toString());
} finally {
close();
}
}
public void updateUser(HashMap<String, String> list, int uid) {
ContentValues values = new ContentValues();
open();
try {
for (String str : list.keySet())
values.put(str, list.get(str));
long rows = sqLiteDatabase.update(SQLitHelper.TblUser, values, "uid=" + uid, null);
} catch (Exception e) {
Log.e(TAG, "insertUser " + e.toString());
} finally {
close();
}
}
public int getUserRecordCount() {
int count = 0;
try {
open();
Cursor cursor = sqLiteDatabase.rawQuery("Select * from " + SQLitHelper.TblUser, null);
count = cursor.getCount();
cursor.close();
} catch (Exception e) {
Logger.debugLog(TAG, "userCount : " + e.toString());
} finally {
close();
}
return count;
}
public HashMap<String,String> getUserDetail(){
HashMap<String, String> list = new HashMap<>();
Cursor cursor = null;
try {
open();
cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + SQLitHelper.TblUser, null);
if (cursor.getColumnCount() > 0) {
while (cursor.moveToNext()) {
list.put("uid", cursor.getString(cursor.getColumnIndex("uid")));
list.put("fname", cursor.getString(cursor.getColumnIndex("fname")));
list.put("lname", cursor.getString(cursor.getColumnIndex("lname")));
list.put("default_zone", cursor.getString(cursor.getColumnIndex("default_zone")));
list.put("teacher", cursor.getString(cursor.getColumnIndex("teacher")));
list.put("student", cursor.getString(cursor.getColumnIndex("student")));
list.put("parent", cursor.getString(cursor.getColumnIndex("parent")));
list.put("email", cursor.getString(cursor.getColumnIndex("email")));
list.put("gender", cursor.getString(cursor.getColumnIndex("gender")));
list.put("birthdate", cursor.getString(cursor.getColumnIndex("birthdate")));
list.put("profilepic", cursor.getString(cursor.getColumnIndex("profilepic")));
list.put("sch_name", cursor.getString(cursor.getColumnIndex("sch_name")));
list.put("login_with", cursor.getString(cursor.getColumnIndex("login_with")));
}
}
} catch (Exception e) {
Logger.debugLog(TAG, "getUserDetail : " + e.toString());
} finally {
close();
if (cursor != null)
if (!cursor.isClosed())
cursor.close();
}
return list;
}
public boolean deleteUserList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblUser, null, null) > 0){
return true;
}else {
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteUserList : " + e.toString());
} finally {
close();
}
return false;
}
public boolean insertClassList(MClassList mClassList) {
try {
open();
ContentValues contentValues = new ContentValues();
contentValues.put("cid", mClassList.getId());
contentValues.put("uid", mClassList.getUid());
contentValues.put("title", mClassList.getTitle());
contentValues.put("color", mClassList.getColor());
contentValues.put("startdate", mClassList.getStartdate());
contentValues.put("enddate", mClassList.getEnddate());
contentValues.put("qrcode", mClassList.getQrcode());
contentValues.put("createdate", mClassList.getCreatedate());
contentValues.put("status", mClassList.getStatus());
contentValues.put("not_submitted_count", mClassList.getNot_sub_count());
long id = sqLiteDatabase.insert(SQLitHelper.TblClassList, null, contentValues);
Logger.debugLog(TAG, "insertClassList : Sus");
return true;
} catch (Exception e) {
Logger.debugLog(TAG, "insertClassList : " + e.toString());
} finally {
close();
}
return false;
}
public ArrayList<MClassList> getClassList() {
ArrayList<MClassList> clssArrayList = new ArrayList<>();
Cursor cursor = null;
try {
open();
String Query = QueryBuilder.classListQuery();
cursor = sqLiteDatabase.rawQuery(Query, null);
if (cursor.getColumnCount() > 0) {
while (cursor.moveToNext()) {
MClassList mClassList = new MClassList();
mClassList.setId(cursor.getInt(cursor.getColumnIndex("cid")));
mClassList.setUid(cursor.getInt(cursor.getColumnIndex("uid")));
mClassList.setTitle(cursor.getString(cursor.getColumnIndex("title")));
mClassList.setColor(cursor.getString(cursor.getColumnIndex("color")));
mClassList.setStartdate(cursor.getString(cursor.getColumnIndex("startdate")));
mClassList.setEnddate(cursor.getString(cursor.getColumnIndex("enddate")));
mClassList.setQrcode(cursor.getString(cursor.getColumnIndex("qrcode")));
mClassList.setCreatedate(cursor.getString(cursor.getColumnIndex("createdate")));
mClassList.setStatus(cursor.getString(cursor.getColumnIndex("status")));
mClassList.setNot_sub_count(cursor.getString(cursor.getColumnIndex("not_submitted_count")));
clssArrayList.add(mClassList);
}
}
} catch (Exception e) {
Logger.debugLog(TAG, "getClassList : " + e.toString());
} finally {
close();
if (cursor != null)
if (!cursor.isClosed())
cursor.close();
}
return clssArrayList;
}
public boolean deleteClassList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblClassList, null, null) > 0){
return true;
}else {
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteClassList : " + e.toString());
} finally {
close();
}
return false;
}
public boolean deleteStudentList() {
try {
open();
if (sqLiteDatabase.delete(SQLitHelper.TblStudentList, null, null) > 0){
return true;
}
else{
return false;
}
} catch (Exception e) {
Logger.debugLog(TAG, "deleteStudentList : " + e.toString());
} finally {
close();
}
return false;
}
public void deleteStudent(int cid,int uid) {
try {
open();
sqLiteDatabase.delete(SQLitHelper.TblStudentList, "uid=" + uid + " AND cid=" + cid, null);
} catch (Exception e) {
Logger.debugLog(TAG, "deleteStudent : " + e.toString());
} finally {
close();
}
}
}
Create class QueryBuilder
public class QueryBuilder {
public static String teacherABCList(int cid) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatDate = df.format(c.getTime()).toString();
String Query = "SELECT * FROM " + SQLitHelper.TblTeacherHomeworkAll + " WHERE cid='" + cid + "'" + " AND duedate>= " +"'"+ formatDate+"'" + " ORDER BY duedate DESC ";
return Query;
}
==============================
public static String studentXXXListQuery(int uid,String status) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatDate = df.format(c.getTime()).toString();
String Query = "SELECT * FROM " + SQLitHelper.TblStudentHomeworkAll + " WHERE uid='" + uid + "'" + " AND status= " +"'"+ status+"'"+" AND isDone='N'" + " ORDER BY duedate DESC ";
return Query;
}
===========================================
public static String studentListQuery(String questionID) {
String query = "SELECT * FROM " + SQLitHelper.TblStudentCheckAnswer + " WHERE qid=" + questionID;
return query;
}
}
use below example to create database
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ayconsultancy.sumeshmedicals.SumeshMedicalContext;
import com.ayconsultancy.sumeshmedicals.model.PlaceModel;
import com.ayconsultancy.sumeshmedicals.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Admin33 on 16-02-2016.
*/
public class DBHelper extends SQLiteOpenHelper {
static String DATABASE_NAME = "sumesh_medicals";
static int DATABASE_VERSION = 1;
static DBHelper dbHelperInstance;
static SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance() {
if (dbHelperInstance == null) {
dbHelperInstance = new DBHelper(SumeshMedicalContext.getContext());
}
return dbHelperInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
Utils.ShowLogD("in sqlite oncreate");
try {
db.execSQL(DBQueries.CREATE_OTC_TABLE);
db.execSQL(DBQueries.CREATE_SHOP_DETAILS_TABLE);
db.execSQL(DBQueries.CREATE_USER_DETAILS_TABLE);
db.execSQL(DBQueries.CREATE_CITY_TABLE);
} catch (Exception e) {
e.printStackTrace();
}
// insertIntoShopDetails(db);
// insertIntoOTcPrescrion(db);
}
public synchronized SQLiteDatabase getDababase() {
if (db == null || (db != null && !db.isOpen())) {
db = this.getWritableDatabase();
}
return db;
}
public synchronized void close() {
super.close();
if (db != null)
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
to save data into sqlite use following first in main
public class MainActivity extends AppCompatActivity {
String one,two;
EditText name,phone;
Button saveButton;
List<StudentModel> list = new ArrayList<StudentModel>();
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(getApplicationContext());
saveButton=(Button)findViewById(R.id.submit);
name=(EditText)findViewById(R.id.textName);
phone=(EditText)findViewById(R.id.textPhone);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StudentModel student = new StudentModel();
student.name = name.getText().toString();
student.phone_number = phone.getText().toString();
db.addStudentDetail(student);
list = db.getAllStudentsList();
print(list);
}
});
}
private void print(List<StudentModel> list) {
String value = "";
for(StudentModel sm : list){
value = value+"id: "+sm.id+", name: "+sm.name+" Ph_no: "+sm.phone_number+"\n";
}
Log.i("<<<<<<<<<<",value);
}
}
then create handler class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Name
public static String DATABASE_NAME = "student_database";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_STUDENTS = "students";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PHONENUMBER = "phone_number";
public static String TAG = "tag";
private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
+ TABLE_STUDENTS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_PHONENUMBER + " TEXT );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_STUDENTS);
onCreate(db);
}
public long addStudentDetail(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values
ContentValues values = new ContentValues();
values.put(KEY_NAME, student.name);
values.put(KEY_PHONENUMBER, student.phone_number);
// insert row in students table
long insert = db.insert(TABLE_STUDENTS, null, values);
return insert;
}
public int updateEntry(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values
ContentValues values = new ContentValues();
values.put(KEY_NAME, student.name);
values.put(KEY_PHONENUMBER, student.phone_number);
return db.update(TABLE_STUDENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(student.id) });
}
public void deleteEntry(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_STUDENTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
}
public StudentModel getStudent(long id) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_STUDENTS + " WHERE "
+ KEY_ID + " = " + id;
Log.d(TAG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndex(KEY_ID));
students.phone_number = c.getString(c.getColumnIndex(KEY_PHONENUMBER));
students.name = c.getString(c.getColumnIndex(KEY_NAME));
return students;
}
public List<StudentModel> getAllStudentsList() {
List<StudentModel> studentsArrayList = new ArrayList<StudentModel>();
String selectQuery = "SELECT * FROM " + TABLE_STUDENTS;
Log.d(TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndex(KEY_ID));
students.phone_number = c.getString(c
.getColumnIndex(KEY_PHONENUMBER));
students.name = c.getString(c.getColumnIndex(KEY_NAME));
studentsArrayList.add(students);
} while (c.moveToNext());
}
return studentsArrayList;
}
}
then set and get the values
public class StudentModel {
public int id;
public String name;
public String phone_number;
public StudentModel(int id, String name, String phone_number) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
this.phone_number = phone_number;
}
public StudentModel(){
}
}
try it
Here is my code how to use sqlite database
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "loginDB.db", null, 1);
getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query = "create table registration (id INTEGER,Image BLOB,firstname VARCHAR,Lastname VARCHAR,DateOfBirth VARCHAR,Phone VARCHAR,Gender VARCHAR, Email VARCHAR primary key,Password VARCHAR);";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//method for insert data
public boolean insertRecord(byte[] imageInByte,String fn) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Image", imageInByte);
contentValues.put("Firstname", fn);
db.insert("signup", null, contentValues);
return true;
}
public boolean updaterecord(String fn,String ln,String unme){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Firstname", fn);
contentValues.put("Lastname", ln);
contentValues.put("Username", unme);
return db.update(TABLE_NAME, contentValues, "Username = ?", new String[]{(unme)}) > 0;
}
public boolean deleterecord(String FirstName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "Firstname = ?", new String[]{FirstName}) > 0;
}
public int displayDetail(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);
return cursor.getCount();
}
public ArrayList displayDetails(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);
ArrayList<ModelClass> arrayList = new ArrayList();
ModelClass model;
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
model = new Model();
model.setFirstname(cursor.getString(cursor.getColumnIndex("Firstname")));
model.setLastname(cursor.getString(cursor.getColumnIndex("Lastname")));
arrayList.add(model);
}
}
}
return arrayList;
}
}
Here is complete code for SQLite database and basic query.
public class SqliteHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
private Context mContext;
public static final String DATABASE_NAME = "DemoDB";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String USER_ID = "id";
public static final String USER_NAME = "username";
public static final String USER_EMAIL = "email";
public static final String USER_PASSWORD = "password";
public static final String CREATE_QUERY_USER_TABLE = " CREATE TABLE " + TABLE_USERS
+ " ( "
+ USER_ID + " INTEGER PRIMARY KEY, "
+ USER_NAME + " TEXT, "
+ USER_EMAIL + " TEXT, "
+ USER_PASSWORD + " TEXT"
+ " ) ";
public SqliteHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
}
// Method to openthe Database
public void openDataBase() throws SQLException {
db = getWritableDatabase();
}
// Method to close the Database
public void close() {
if (db != null && db.isOpen()) {
db.close();
}
}
public boolean isEmailExists(String email) {
boolean isUserFound = false;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]{email.trim()});
if (cursor != null) {
if(cursor.getCount() > 0) {
isUserFound = true;
}
cursor.close();
}
return isUserFound;
}
public void addUser(User user) {
ContentValues values = new ContentValues();
values.put(USER_NAME, user.userName);
values.put(USER_EMAIL, user.email);
values.put(USER_PASSWORD, user.password);
long todo_id = db.insert(TABLE_USERS, null, values);
}
public boolean login(User user) {
boolean isLogin = false;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]{user.email.trim()});
if (cursor != null) {
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
String pass = cursor.getString(cursor.getColumnIndex(USER_PASSWORD));
if (pass != null && user.password.equalsIgnoreCase(pass.trim())) {
isLogin = true;
}
}
cursor.close();
}
return isLogin;
}
}
I wanna make a database in sqlite android ,and I wanna create 2 table in database ,and after that I wanna create tables dynamically. but my class DBAdapter just create one table and for other tables throws error "no such table" so what should I do for this? plz help me
package com.example.asa;
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_con = "_id";
public static final String KEY_NAME_con = "name";
public static final String KEY_NUMBER_con = "number";
private static final String TAG = "DBAdapter";
private static final String DATABASE_TABLE_con = "contacts";
private static final String DATABASE_NAME = "MyDB";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_con =
"create table contacts (_id integer primary key autoincrement, "
+ "name text not null, number 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)
{
try {
db.execSQL(DATABASE_CREATE_con);
} 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 chats");
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 contact into the database---
public long insertContact(String name, String number)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME_con, name);
initialValues.put(KEY_NUMBER_con, number);
return db.insert(DATABASE_TABLE_con, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE_con, KEY_ROWID_con + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE_con, new String[] {KEY_ROWID_con, KEY_NAME_con,
KEY_NUMBER_con}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE_con, new String[] {KEY_ROWID_con,
KEY_NAME_con, KEY_NUMBER_con}, KEY_ROWID_con + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String number)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME_con, name);
args.put(KEY_NUMBER_con, number);
return db.update(DATABASE_TABLE_con, args, KEY_ROWID_con + "=" + rowId, null) > 0;
}
//---Search Contact by String ---//
public String Search(String str)
{
String [] columns = new String[]{ KEY_ROWID_con, KEY_NAME_con, KEY_NUMBER_con};
return db.query(DATABASE_TABLE_con, columns, KEY_NAME_con + "=?", new String[] { str }, null, null, null).getString(0);
}
//---insert a contact into the database---
}
try this.I was having the same problem and this solved it--
package db;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB_Handler_exercise extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "exercise_items";
private static final int DATABASE_VERSION = 1;
//table name
private static final String TABLE_EXERCISE_TOP = "exercise_top";
private static final String TABLE_EXERCISE_BOTTOM = "exercise_bottom";
private static final String TABLE_EXERCISE_CARDIO = "exercise_cardio";
private static final String TABLE_EXERCISE_VARIATIONS= "exercise_variations";
//column name
private static final String KEY_EX_ID = "ex_id";
private static final String KEY_EX_NAME = "ex_name";
private static final String KEY_EX_NICKNAME = "ex_nickname";
private static final String KEY_NO_VARIATION = "ex_variation";
private static final String KEY_MAIN_ID = "main_id";
private static final String KEY_VARIATION_ID = "v_id";
private static final String KEY_EX_VARIATION_NAME = "ex_variation_name";
private static final String KEY_EX_VARIATION_STEPS= "ex_variation_steps";
private static final String KEY_EX_VARIATION_PHOTOS = "ex_variation_photos";
public DB_Handler_exercise(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
super.onDowngrade(db, oldVersion, newVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//create table exercise_top
String CREATE_TABLE_TOP="CREATE TABLE IF NOT EXISTS "+TABLE_EXERCISE_TOP + "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," + KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" + ")";
db.execSQL(CREATE_TABLE_TOP);
//create table exercise_bottom
String CREATE_TABLE_BOTTOM="CREATE TABLE IF NOT EXISTS " + TABLE_EXERCISE_BOTTOM+ "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," +KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" +")";
db.execSQL(CREATE_TABLE_BOTTOM);
//create table exercise_cardio
String CREATE_TABLE_CARDIO="CREATE TABLE IF NOT EXISTS "+ TABLE_EXERCISE_CARDIO+ "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," +KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" +")";
db.execSQL(CREATE_TABLE_CARDIO);
//create table exercise_variations
String CREATE_TABLE_VARIATION="CREATE TABLE IF NOT EXISTS "+ TABLE_EXERCISE_VARIATIONS+ "(" + KEY_MAIN_ID + " INTEGER ," + KEY_VARIATION_ID + " INTEGER,"+ KEY_EX_NAME+" TEXT,"+ KEY_EX_NICKNAME+" TEXT," + KEY_EX_VARIATION_NAME + " TEXT," +KEY_EX_VARIATION_STEPS + " TEXT," + KEY_EX_VARIATION_PHOTOS + " TEXT" +")";
db.execSQL(CREATE_TABLE_VARIATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
//adding data on table_top
public void addData_top(Table_exercise_top top){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, top.getEx_id());
values.put(KEY_EX_NAME, top.getEx_name());
values.put(KEY_EX_NICKNAME, top.getEx_nickname());
values.put(KEY_NO_VARIATION, top.getEx_variation());
db.insert(TABLE_EXERCISE_TOP, null, values);
db.close();
}
//adding data on table_bottom
public void addData_bottom(Table_exercise_bottom bottom){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, bottom.getEx_id());
values.put(KEY_EX_NAME, bottom.getEx_name());
values.put(KEY_EX_NICKNAME, bottom.getEx_nickname());
values.put(KEY_NO_VARIATION, bottom.getEx_variation());
db.insert(TABLE_EXERCISE_BOTTOM, null, values);
db.close();
}
//adding data on table_cardio
public void addData_cardio(Table_exercise_cardio cardio){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, cardio.getEx_id());
values.put(KEY_EX_NAME, cardio.getEx_name());
values.put(KEY_EX_NICKNAME, cardio.getEx_nickname());
values.put(KEY_NO_VARIATION, cardio.getEx_variation());
db.insert(TABLE_EXERCISE_CARDIO, null, values);
db.close();
}
//adding data on table_variation
public void addData_variation(Table_variation variation){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_MAIN_ID, variation.getMain_id());
values.put(KEY_VARIATION_ID, variation.getV_id());
values.put(KEY_EX_NAME, variation.getEx_name());
values.put(KEY_EX_NICKNAME, variation.getEx_nickname());
values.put(KEY_EX_VARIATION_NAME, variation.getVariation_name());
values.put(KEY_EX_VARIATION_STEPS, variation.getVariation_steps());
values.put(KEY_EX_VARIATION_PHOTOS, variation.getVariation_photos());
db.insert(TABLE_EXERCISE_VARIATIONS, null, values);
db.close();
}
}
I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
So this is my code:
public void onItemClick(AdapterView<?> listView, View view, int position, long id)
{
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int _id = cursor.getInt(0);
String _recipe = cursor.getString(1);
Intent intent = new Intent(Luzon1Activity.this,RecipeInstruction.class);
intent.putExtra("id", _id);
intent.putExtra("recipe", _recipe);
startActivity(intent);
}
This is my code for the next activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipeinstruction);
dbHelper = new Dbadapter(this);
dbHelper.open();
bg = (RelativeLayout) findViewById(R.id.relativeLayout1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getInt("id");
recipe = extras.getString("recipe");
}
Toast.makeText(this, id+"\n"+recipe, Toast.LENGTH_SHORT).show();
bg.setBackgroundResource(getImageId(this, recipe));
}
My problem is on this part: String _recipe = cursor.getString(1).
It always gives me the wrong data. I tried to change the number but still it gives me the wrong data.
This is my database:
package com.pinoycookbook;
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 ROWID = "_id";
public static final String NAME = "foodname";
public static final String ORIGIN = "origin";
public static final String RECIPE = "recipe";
public static final String CATEGORY = "category";
private static final String TAG = "Dbadapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "PinoyCookbook.sqlite";
public static final String SQLITE_TABLE = "Food";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
ROWID + " integer PRIMARY KEY autoincrement," +
NAME + " TEXT," +
RECIPE + " TEXT," +
ORIGIN + " TEXT," +
CATEGORY+ " TEXT,"+
" UNIQUE (" + ROWID +"));";
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public Dbadapter(Context ctx) {
this.mCtx = ctx;
}
public Dbadapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createData(String foodname, String recipe, String origin, int i) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME, foodname);
initialValues.put(RECIPE, recipe);
initialValues.put(ORIGIN, origin);
initialValues.put(CATEGORY, i);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllData() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertData() {
createData("Adobong Manok","adobongmanok","Manila",1);
createData("Lechon","lechon","Cebu",2);
createData("Crispy Pata","crispypata","Cebu",2);
createData("Bulalo","bulalo","Batangas",1);
createData("Taba ng Talangka Rice","talangkarice","Roxas",2);
createData("Arroz Caldo","arrozcaldo","Roxas",2);
createData("Sinigang","sinigang","Manila",1);
}
}
So i recommend you to use getColumnIndex() method rather than hardcode it.
String _recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));
It will ensure that you will get always right field. And if it still get wrong data problem is in query not in Cursor
Note: An usage of static fields that hold column names is always the best practise.
Update:
I've tried it before and it gives me this error:
java.lang.IllegalArgumentException: column 'recipe' does not exist
You need to find out your actual table structure. Try to perform this statement:
PRAGMA table_info(Dbadapter.SQLITE_TABLE);
What says docs(source):
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Example:
Here i created for you method for getting tableinfo via PRAGMA:
public String getTableInfo() {
StringBuilder b = new StringBuilder("");
Cursor c = null;
try {
db = helper.getReadableDatabase();
String query = "pragma table_info(" + Dbadapter.SQLITE_TABLE + ")";
c = db.rawQuery(query, null);
if (c.moveToFirst()) {
do {
b.append("Col:" + c.getString(c.getColumnIndex("name")) + " ");
b.append(c.getString(c.getColumnIndex("type")));
b.append("\n");
} while (c.moveToNext());
}
return b.toString();
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
Output will be something like this:
Column: type text
Column: date text
Only for imagination i will give you screen:
you can try it this way:
cursor.getString(cursor.getColumnIndex("recipe"));
it returns you the correct index and as result the correct value.