SQLite Database Error - No column named task - java

Error_Database
enter code here
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String NAME = "toDoListDatabase";
private static final String TODO_TABLE = "todo";
private static final String ID = "id";
private static final String TASK = "task";
private static final String STATUS = "status";
private static final String CREATE_TODO_TABLE = "CREATE TABLE " + TODO_TABLE + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TASK + " TEXT, "
+ STATUS + " INTEGER)";
private SQLiteDatabase db;
public DataBaseHandler(Context context) {
super(context, NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE);
// Create tables again
onCreate(db);
}
public void openDatabase() {
db = this.getWritableDatabase();
}
public void insertTask(ToDoModel task){
ContentValues cv = new ContentValues();
cv.put(TASK, task.getTask());
cv.put(STATUS, 0);
db.insert(TODO_TABLE, null, cv);
}
public List<ToDoModel> getAllTasks(){
List<ToDoModel> taskList = new ArrayList<>();
Cursor cur = null;
db.beginTransaction();
try{
cur = db.query(TODO_TABLE, null, null, null, null, null, null, null);
if(cur != null){
if(cur.moveToFirst()){
do{
ToDoModel task = new ToDoModel();
task.setId(cur.getInt(cur.getColumnIndexOrThrow(ID)));
task.setTask(cur.getString(cur.getColumnIndexOrThrow(TASK)));
task.setStatus(cur.getInt(cur.getColumnIndexOrThrow(STATUS)));
taskList.add(task);
}
while(cur.moveToNext());
}
}
}
finally {
db.endTransaction();
assert cur != null;
cur.close();
}
return taskList;
}
public void updateStatus(int id, int status){
ContentValues cv = new ContentValues();
cv.put(STATUS, status);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void updateTask(int id, String task) {
ContentValues cv = new ContentValues();
cv.put(TASK, task);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void deleteTask(int id){
db.delete(TODO_TABLE, ID + "= ?", new String[] {String.valueOf(id)});
}
}
Can somebody proofread this? The error is :
"no column named task in "INSERT INTO todo(status,task) VALUES (?,?)"
"android.database.sqlite.SQLiteException: table todo has no column named task (code 1 SQLITE_ERROR): , while compiling: INSERT INTO todo(status,task) VALUES (?,?)".
I also attached a ss of the error as a link.
I'm trying to create a database where I can store tasks. Does anyone has a fix for this?
Thanks!

If you're on an emulator, try reinstalling the application! It works sometimes.

Related

Interchange ids of android database

How to go about if i want to interchange the contents of my android data base as shown below:
before
1 hello world
2 Android Nougat
after
1 Android Nougat
2 hello world
You don't need to change the positions in Database. You need to add additional int value to a database (not id). And change this value according to a new position. For first object you make it 2; for a second - 1. And when you retrieve data from your database you just sort it according to this value.
Example
String orderBy = "POSITION ASC";
Cursor cursor = database.query(TABLE_NAME, logTableColumns, null, null,
null, null, orderBy);
public class QueueDatabase extends SQLiteOpenHelper {
public QueueDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "queue.sqlite";
//Table names
public static final String TABLE_QUEUE = "Queue";
public static final String KEY_ID = "id";
public static final String KEY_SNAME = "key_sname";
public static final String KEY_ANAME = "key_aname";
public static final String KEY_URL = "key_url";
public static final String KEY_ORDER = "key_order";
public static final String CREATE_TABLE_QUEUE= "CREATE TABLE IF NOT EXISTS "
+ TABLE_QUEUE
+ "("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_SNAME
+ " TEXT,"
+ KEY_ANAME
+ " TEXT,"
+ KEY_URL
+ " TEXT,"
+ KEY_ORDER
+ " TEXT "
+")";
public long insertQueue(ArrayList<Music> mTaskArr)
{
long row_id = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i = 0;i<mTaskArr.size() ;i++) {
values.put(KEY_SNAME, mTaskArr.get(i).getTitle());
values.put(KEY_ANAME, mTaskArr.get(i).getArtist());
values.put(KEY_URL, mTaskArr.get(i).getUrl());
row_id = db.insert(TABLE_QUEUE, null, values);
}
db.close();
return row_id;
}
public void updateOrder(long rowID, int newPos) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ORDER, newPos);
db.update(TABLE_QUEUE, cv, KEY_ID + "=" + rowID, null);
}
public boolean updateQueue (Integer id, String S, String A, String U) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SNAME,S);
contentValues.put(KEY_ANAME,A);
contentValues.put(KEY_URL,U);
db.update(TABLE_QUEUE, contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public void dropTable() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "drop table " + TABLE_QUEUE;
try {
db.execSQL(sql);
} catch (SQLException e) {
System.out.println(e);
}
}
public ArrayList<Music> getAllQueue() {
ArrayList<Music> ar = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_QUEUE;
//Log.d("QUERY",""+selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Music r = new Music();
r.setId(c.getInt(c.getColumnIndex(KEY_ID)));
r.setTitle( c.getString(c.getColumnIndex(KEY_SNAME)));
r.setArtist( c.getString(c.getColumnIndex(KEY_ANAME)));
r.setUrl(c.getString(c.getColumnIndex(KEY_URL)));
ar.add(r);
} while (c.moveToNext());
}
db.close();
return ar;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUEUE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void arrange() {
SQLiteDatabase db = this.getWritableDatabase();
String[] rank = new String[]{ QueueDatabase.KEY_ID };
Cursor c = db.query(QueueDatabase.TABLE_QUEUE, rank, null, null, null, null, QueueDatabase.KEY_ORDER+" ASC");
}
}
this is how u enter data in database:
q.add(new Music(T, U, A));
qd.insertQueue(q);

edit content in database SQLiteDatabase

I created a database with SQLiteDatabase, everything works fine, except when I want to change the content of some columns .. I'm using db.update, but it seems not work. someone can help me understand what I'm doing wrong? thank you all
public class Note_DBHelper extends SQLiteOpenHelper {
private Context ctx;
//version of database
private static final int version = 1;
//database name
private static final String DB_NAME = "notesDB";
//name of table
private static final String TABLE_NAME = "notes";
//column names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "noteTitle";
private static final String KEY_CONTENT = "noteContent";
private static final String KEY_TESTO = "noteTesto";
private static final String KEY_TXT_COLORE = "noteColore";
private static final String KEY_DATE = "date";
//sql query to creating table in database
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_TITLE+" TEXT NOT NULL, "+KEY_CONTENT+" TEXT NOT NULL,"+KEY_TESTO+" TEXT NOT NULL, "+KEY_TXT_COLORE+" TEXT NOT NULL, "+KEY_DATE+" TEXT);";
//contructor of Note_DBHelper
public Note_DBHelper(Context context) {
super(context, DB_NAME, null, version);
this.ctx = context;
}
//creating the table in database
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
//in case of upgrade we're dropping the old table, and create the new one
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
//function for adding the note to database
public void addNote(String title, String content,String testo, String txt_colore) {
SQLiteDatabase db = this.getWritableDatabase();
//creating the contentValues object
//read more here -> http://developer.android.com/reference/android/content/ContentValues.html
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
//inserting the note to database
db.insert(TABLE_NAME, null, cv);
//closing the database connection
db.close();
//see that all database connection stuff is inside this method
//so we don't need to open and close db connection outside this class
}
//getting all notes
public Cursor getNotes(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO,KEY_TXT_COLORE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNotes2(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_ID, KEY_TITLE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNote(SQLiteDatabase db, int id) {
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO, KEY_TXT_COLORE, KEY_DATE}, KEY_ID + " = ?", new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
return c;
}
public void removeNote(int id) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] { String.valueOf(id) });
db.close();
}
public void updateNote(String title, String content,String testo, String txt_colore, String editTitle) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
db.update(TABLE_NAME, cv, KEY_TITLE + " LIKE '" + editTitle + "'", null);
db.close();
}
Use this
db.update(TABLE_NAME, cv, KEY_ID + "=" + id, null);
then in your createNote class
dbhelper.updateNote(title, content, id);

How do I use SQLite in android?

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

Android Sqlite shows no such table

i want to add some image uri's to the Database. my Database table has two columns id and String Uri. The Problem is it shows No such table exist when trying to insert some Uris to Table. Here is my Code of Database Adapter Class.
package com.example.mystorage;
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 {
// for customer registration
static final String KEY_ID = "id";
static final String KEY_URI = "uri";
static final String DATABASE_NAME = "IMAGE_DB";
static final String DATABASE_TABLE = "temp_images1";
static final int DATABASE_VERSION = 2;
static final String DATABASE_CREATE = "create table temp_images1 (id integer autoincrement, "
+ "uri text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS temp_images1");
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
// //////////////////////////////////////for
// customerRegistration////////////////
// customer registration for retrieve data
public Cursor getAllImages() {
return db.query(DATABASE_TABLE, new String[] {KEY_URI}, null,
null, null, null, null);
}
public Cursor getContentimage(long id) throws SQLException {
Cursor c = db.query(true, DATABASE_TABLE,
new String[] { KEY_ID, KEY_URI },
KEY_ID + "=" + id, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// customer registration for update data
public boolean updateimages(long id, String uri) {
ContentValues args = new ContentValues();
// args.put(KEY_ID,id);
args.put(KEY_URI, uri);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + id, null) > 0;
}
// customer registration for insert data
public long insertImages(String uri) {
ContentValues args = new ContentValues();
//args.put(KEY_ID, id);
args.put(KEY_URI, uri);
long n = db.insert(DATABASE_TABLE, null, args);
//db.insertOrThrow(DATABASE_TABLE, null, args);
return n;
}
// customer registration for remove data
public boolean deleteImages(long id) {
return db.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
}
here is My ImageAdapter class where i am calling the insert method.
mThumbs is uri Arraylist to Store the Content of Database While Retrieving.
public ImageAdapter(Context c, android.net.Uri uri) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
db.insertImages(uri.toString());
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
public ImageAdapter(Context c, ArrayList<Uri> imageUris) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
for (int i = 0; i < imageUris.size(); i++){
db.insertImages(imageUris.get(i).toString());
}
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
private void upadteAllImages() {
mTHumbs.clear();
try{
db.open();
Cursor c = db.getAllImages();
if (c.moveToFirst()) {
while (c.moveToNext()){
String uri = c.getString(1);
mTHumbs.add(Uri.parse(uri));
}
}
//mTHumbs.add((Uri) db.getAllImages());
db.close();
}catch(Exception e){
e.printStackTrace();
}
}
String query = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_URI + " TEXT not null "+)";
Fix the syntax error in your CREATE TABLE. AUTOINCREMENT can only be used with INTEGER PRIMARY KEY and you're missing the PRIMARY KEY.
Remove the try-catch in your onCreate() so that you get an exception in case of a syntax problem.
Uninstall your app so that the old database is removed and your helper onCreate() gets run again with the fixed SQL.
Some minor changes are required to create a table in database.
Please see this-
" CREATE TABLE temp_images1 ( id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "uri TEXT NOT NULL ) ; ";

My program can not find tables in sqlite database on Android

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.

Categories

Resources