Selecting Specific rows from SQLite Database-ANDROID-SQLite Database - java

I am working on databases for my project and I have columns for primary key (rowid), number (contact number) and name. I am adding two different entries with same number in my database and i need to extract both of them from the database. Code for extracting is
public Cursor SelectList(String number) throws SQLException {
String query = "SELECT FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";
Cursor mcursor = db.rawQuery(query, null);
if(mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
But it is showing SQLite exception at this line
Cursor mcursor = db.rawQuery(query, null);
Code for DatabaseHandler
package com.example.gul.databasealvie;
/**
* Created by gul on 6/6/15.
*/
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 {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_NUMBER = "number";
static final String KEY_ID="listid";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB20";
static final String DATABASE_TABLE = "contacts5";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE= "create table contacts5(_id integer primary key , "
+ "name text not null, number text not null, listid 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
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public boolean DeleteList(String number){
db.execSQL("DELETE FROM "+DATABASE_TABLE+" WHERE "+KEY_NUMBER+"="+number);
return true;
}
public void DropTable(){
db.execSQL("Delete From " + DATABASE_TABLE);
}
public Cursor SelectList(String number) throws SQLException {
String query = "SELECT FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";
Cursor mcursor = db.rawQuery(query,null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(TableData contact, String id )
{
long myid=Long.parseLong(id);
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, contact.getName());
initialValues.put(KEY_NUMBER,contact.getPhoneNumber());
initialValues.put(KEY_ID, id);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean DeletContact(String number)throws SQLException{
return db.delete(DATABASE_TABLE, KEY_NUMBER + "=" + number, null) > 0;
}
public long insertContact(Anonymous contact, String id )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, contact.getName());
initialValues.put(KEY_NUMBER, contact.getPhoneNumber());
initialValues.put(KEY_ID, id);
// Log.d("Contact", contact.getName() + contact.getPhoneNumber());
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteContact(String number)
{
return db.delete(DATABASE_TABLE, KEY_NUMBER + " = ?",
new String[] { number }) > 0;
}
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_NUMBER}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_NUMBER}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean iskey(long rowid)throws SQLException
{
Cursor mCursor=db.query(true,DATABASE_TABLE, new String[]{KEY_ROWID,KEY_NAME,KEY_NUMBER },KEY_ROWID+"="+rowid,null,null
,null,null,null);
if(mCursor!=null && mCursor.moveToFirst()){
return true;
}
else
return false;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_NUMBER, email);
return db.update(
DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
Code for testing purposes
package com.example.gul.databasealvie;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
DBAdapter db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
AddContact();
PrintingList();
GetContacts();
GetContact();
//UpdateContact();
DeleteContact();
}
public void AddContact() {
Anonymous a= new Anonymous(34,"Wei-Meng Lee", "12345");
Anonymous b= new Anonymous(2,"Wejhkjh Lee", "12234");
//---add a contact---
db.open();
if (db.insertContact(a,"22") >= 0){
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
if (db.insertContact(b,"21") >= 0) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
if (db.insertContact(b,"21") >= 0) {
Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
}
db.close();
}
public void PrintingList(){
db.open();
Cursor mCursor=db.SelectList("12234");
if(mCursor.moveToFirst()){
do {
displaylist(mCursor);
}while(mCursor.moveToNext());
}
db.close();
}
public void GetContacts() {
//--get all contacts---
db.open();
// db.DeleteList("12345");
// if(db.DeletContact("12234")) {
// Log.i("Deleted contact", "");
//}
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
public void GetContact() {
//---get a contact---
db.open();
Cursor c = db.getContact(2);
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
db.close();
}
public void UpdateContact() {
//---update a contact---
db.open();
if (db.updateContact(1, "Wei-Meng Lee", "weimenglee#gmail.com"))
Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
db.close();
}
public void DeleteContact() {
db.open();
//if (db.deleteContact(1))
// Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
//else
// Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();
db.close();
}
public void DisplayContact(Cursor c)
{
Log.i(
"contacts", "id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Number: " + c.getString(2)
);
db.open();
if((db.iskey(2))){
Log.i("Yay ", "it's working");
}
db.close();
}
public void displaylist(Cursor c){
Log.i(
"List","listid:"+c.getString(0)+ "\n"+
"NAMElist: " + c.getString(1)+ "\n" +
"list: "+c.getString(2)
);
}
}
Code For Anonymous.java
package com.example.gul.databasealvie;
/**
* Created by gul on 6/6/15.
*/
/**
* Created by Noor Zia on 5/26/2015.
*/
public class Anonymous {
public long id;
public String name;
public String number;
public Anonymous(){
name="Unknown";
}
public Anonymous(String no){
name="Unknown";
number = no;
}
public Anonymous(long id, String name, String number){
name=name;
this.number=number;
this.name=name;
this.id=id;
}
public long getID(){
return this.id;
}
// setting id
// getting name
public String getName(){
return this.name;
}
// setting name
// getting phone number
public String getPhoneNumber(){
return this.number;
}
// setting phone number
}

dbHelper = new DBHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from centuaryTbl where email='"+email+"'",null);
if (cursor.moveToFirst())
{
do
{
String s1 = cursor.getString(cursor.getColumnIndex("s1"));
String s2 = cursor.getString(cursor.getColumnIndex("s2"));
String s3 = cursor.getString(cursor.getColumnIndex("s3"));
}while (cursor.moveToNext());
}

You need to specify the columns to retrieve. For instance:
String query = "SELECT name, number FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim() + "'";
More information about Select clause

Or you can fetch all columns using '*'
Your query will be
String query = "SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_NUMBER + "='" + number.trim()+"'";

public String select_data(String email)
{
db=this.getReadableDatabase();
String query="select email,password from "+Table_name;
Cursor cursor=db.rawQuery(query,null);
String a,b;
b="not found";
if (cursor.moveToFirst()) {
do {
a=cursor.getString(0);
if(a.equals(email))
{
b=cursor.getString(1);
break;
}
} while(cursor.moveToNext());
}
return b;
}

Related

Android Studio SQLite table duplicates everytime I click view button

I have added 2 entries in the database and if I click the view button for the first time, it normally shows the 2 entries. However, if I click the view button again, there will be 4 entries and then 6, 8, 10 etc. Even though there are 4,6,8,10,12 entries if I view it, I used a getCount command and it showed 2 which is correct. So the database is correct so the bug here is somewhere in the viewbtn but I don't know what it is. How do I fix this?
MainActivity.java
viewbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
res = myDb.getAllData();
if(res.getCount()==0){ //when there is no data show message..error message is depend on "showMessage"method
//show message
showMessage("Oops!","No entry, add an entry to see the list.");
return;
}
while(res.moveToNext()) {
// read and collect data in database in column
buffer.append("\n\n");
buffer.append("Date: " + res.getString(0) + "\n");
buffer.append("Time: " + res.getString(1) + "\n");
buffer.append("Name: " + res.getString(2) + "\n");
buffer.append("Surname: " + res.getString(3) + "\n");
buffer.append("ID: " + res.getString(4) + "\n");
buffer.append("--------------------------------------------------------------");
}
//show all data
showMessage("Entries",buffer.toString()); //show all data in list.list is depnd on "showMessage"method
}
});
DatabaseHelper.java
package com.example.AppDraft3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
public static final String DATABASE_NAME="Attendance.db";
public static final String TABLE_NAME="Attendance_table";
public static final String COL_1="DATE";
public static final String COL_2="TIME";
public static final String COL_3="NAME";
public static final String COL_4="SURNAME";
public static final String COL_5="ID";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (DATE TEXT,TIME TEXT,NAME TEXT,SURNAME TEXT,ID INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
}
public Boolean verifyData(String TABLE_NAME, String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE id = '" + id + "'";
Cursor res = db.rawQuery(query, null);
if (res.moveToFirst()){
res.close();
return true;
} else {
res.close();
return false;
}
}
public long insertData(String name,String surname,String id){
if (verifyData(TABLE_NAME, id)){
return 0;
}
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
Date time = new Date();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, dateFormat.format(date));
contentValues.put(COL_2, timeFormat.format(time));
contentValues.put(COL_3, name);
contentValues.put(COL_4, surname);
contentValues.put(COL_5, id);
long result=db.insert(TABLE_NAME, null, contentValues);
return result;
}
public boolean verifyExist(String id){
if (verifyData(TABLE_NAME, id)){
return true;
} else {
return false;
}
}
public Cursor getAllData(){
//get all data
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select*from "+TABLE_NAME, null);
return res;
}
public Integer deleteData(){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,null,null);
}
public Boolean singleDeleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res =db.rawQuery("Select * from " +TABLE_NAME+ " where id = ?", new String[] {id});
if (res.getCount() > 0) {
long resultDel = db.delete(TABLE_NAME, "id=?", new String[] {id});
if (resultDel == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
}
The buffer needs to be empties otherwise you are just appending to it. I am assuming this is a StringBuffer
public void onClick(View v) {
res = myDb.getAllData();
buffer = new StringBuffer();
:
:
}

Why my page automatic close when I login page in SQLite?

My problems : What I suppose to do?
1. Below is my error in logcat
2. Why my data doesn't enter in my SQLite database when I open it in SQLite browser?
3. Almost all the method I make a research and use, but all of them cannot use it.
My connection SQLite database : Database.java
package com.example.projectvote;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class Database extends SQLiteOpenHelper {
private static final String TAG = "Database";
public static final String DbName = "SignUp.db";
public static final String TbName = "SignUp";
public static final String Col1 = "Num";
public static final String Col2 = "ID";
public static final String Col3 = "Password";
public static final String TbName1 = "candidate";
public static final String Col4 = "Nom";
public static final String Col5 = "Candidates";
public Database(Context context) {
super(context, DbName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE SignUp (Num INT PRIMARY KEY AUTOINCREMENT, ID TEXT, Password TEXT)");
sqLiteDatabase.execSQL("CREATE TABLE candidate (Nom INT PRIMARY KEY AUTOINCREMENT, Candidates TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TbName);
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TbName1);
onCreate(sqLiteDatabase);
}
public long addUser(String ID, String password)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ID", ID);
cv.put("password", password);
long res = db.insert("SignUp", null, cv);
db.close();
return res;
}
public boolean checkUser(String ID, String password)
{
String[] columns = { Col2 };
SQLiteDatabase db = getReadableDatabase();
String selection = Col2 + "=?" + "and" + Col3 + "=?";
String[] selectionArgs = { ID, password };
Cursor c = db.query(TbName, columns, selection, selectionArgs, null, null, null);
int count = c.getCount();
c.close();
db.close();
if (count > 0)
return true;
else
return false;
}
public Cursor readData(SQLiteDatabase db) {
String[] cols = { Col5 };
Cursor c = db.query(TbName1, cols, null, null, null, null, null);
return c;
}
public boolean addCandidate(String Candidates)
{
SQLiteDatabase db = this. getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(Col5, Candidates);
Log.d(TAG, "addCandidate : Adding " + Candidates + " to " + TbName1);
long res = db.insert(TbName1, null, cv);
if(res == -1)
{
return false;
}
else
{
return true;
}
}
public Cursor getItemID(String Candidates)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + Col4 + " FROM " + TbName1 + " WHERE " + Col5 + " = " + Candidates + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public void updateCandidate(String newCandidate, int ID, String oldCandidate)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TbName1 + " SET " + Col5 + "= '" + newCandidate + "' WHERE " + Col5 + "= '" + oldCandidate + "'";
Log.d(TAG, "updateCandidate: query: " + query);
Log.d(TAG, "updateCandidate: Setting Candidate to " + newCandidate);
db.execSQL(query);
}
public void deleteCandidate(int ID, String Candidate)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TbName1 + " WHERE " + Col5 + "= '" + Candidate + "'";
Log.d(TAG, "deleteCandidate: query: " + query);
Log.d(TAG, "deleteCandidate: Deleting: " + Candidate + " from database ");
db.execSQL(query);
}
public Cursor getListContent1() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TbName1;
Cursor data = db.rawQuery(query, null);
return data;
}
}
My login java : Login.java
package com.example.projectvote;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity
{
EditText ID, password;
Database db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new Database(this);
ID = findViewById(R.id.etID);
password = findViewById(R.id.etPassword);
}
public void OnLog(View view)
{
String Id = ID.getText().toString().trim();
String Password = password.getText().toString().trim();
Boolean res = db.checkUser(Id, Password);
if (res == true)
{
startActivity(new Intent(getApplicationContext(), Home.class));
}
else if ((ID.equals("Admin") && Password.equals("Admin2019")))
{
startActivity(new Intent(getApplicationContext(), Admin.class));
}
else
{
Toast.makeText(Login.this, "Sorry, Login Error", Toast.LENGTH_SHORT).show();
}
}
public void OnReg(View view) {
startActivity(new Intent(getApplicationContext(), SignUp.class));
}
}
Update your queries in your onCreate() of Database.java like following
sqLiteDatabase.execSQL("CREATE TABLE SignUp (Num INTEGER PRIMARY KEY AUTOINCREMENT, ID TEXT, Password TEXT)");
sqLiteDatabase.execSQL("CREATE TABLE candidate (Num INTEGER PRIMARY KEY AUTOINCREMENT, Candidates TEXT)");

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

Multiple Tables In SQlite android

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

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