Adding a new field in SQLite in android - java

As I said before, im very much new to android and now i faced a very troubling poblem.
I have a database and i need to add a new field in the table. I don't know much of android and java..
So please guys, a little help will be appreciated...
Here's my code for the database:
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);
}
}
This is for the functions for the database:
public class CommentsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };
public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Comment createComment(String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Comment newComment = cursorToComment(cursor);
cursor.close();
return newComment;
}
public void deleteComment(Comment comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
}
and this is the other class which the above class uses:
public class Comment {
private long id;
private String comment;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return comment;
}
}
All this code works fine when I'm working with only one field(i.e. the comment) but
I want to add three new fields named: "Address", "Age", "Gender" and if possible change the DB name and i just can't seem to be able to alter it in the right way to get what i want.
Please tell me the right alterations needed.
PLEASE Help me on this!
Thanks in advance,
Waiting for your reply...

if possible change the DB name and i just can't seem to be able to
alter it in the right way to get what i want. Please tell me the right
alterations needed.
There are two ways:
implement correctly onUpgrade() method of SQLiteOpenHelper class (if you need update)
Just update your database class (modify DDL statement e.q. add new columns and change db
name if you want) and before install updated application to your device, delete
application's data (in device it's in settings under applications
manager). That will delete all data connected to your application
(databases, preferences, etc.)
Look at
Android: upgrading DB version and adding new table

Create new columns in table like this:
String Comment_table = String.format("CREATE TABLE %s " +
"(%s INTEGER PRIMARY KEY AUTOINCREMENT ," +
" %s TEXT , %s TEXT , %s TEXT ," +
" %s TEXT )",
Comment_Table,
Comment_ID ,
Comment , Address , Age ,
Gender );
(Here, Column names are Static String Declared as Class Variables).

Related

Primary key not returned correctly in sqlite database

I am creating an app to understand sqlite database.
enter image description here
Whenever I click add button the name would be added in sqlite database
btnAdd.setOnClickListener(v -> {
DBHelper helper=new DBHelper(MainActivity.this, null, null, 1);
EmployeeData data=new EmployeeData(1, etName.getText().toString());
int id=helper.add(data);
data.setId(id);
Toast.makeText(MainActivity.this, Integer.toString(id), Toast.LENGTH_SHORT).show();
});
EmployeeData just contains constructor and getters and setters for the arguments.
DBHelper code:
public int add(EmployeeData data){
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(NAME, data.getName());
db.insert(TABLE_NAME, null, cv);
String sql="SELECT * FROM "+TABLE_NAME+" WHERE "+NAME+" = "+"'"+data.getName()+"'";
Cursor c=db.rawQuery(sql, null);
int id;
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex(ID));
}else {
id=-1;
}
c.close();
db.close();
return id;
}
Consider I am entering "Aditya" in the edit text, I am getting a toast message of 1.
But when I change the name as "Adity" I am still getting a toast message of 1.
Why isn't primary key of second record changing?
I even tried adding AUTOINCREMENT but it doesn't work.
What is the problem?
Btw the 1 in employee data constructor has no relation to the primary key
Database creation:
#Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE "+TABLE_NAME+" ( "+ID+" INTEGER PRIMARY KEY, "+NAME+" VARCHAR2(25))";
db.execSQL(sql);
}
If you look at the insert method. It returns the id, as a long, of the inserted row else -1 if the row was not inserted.
In theory the id can be a long, as such it is recommended that long instead of int is used.
Assuming that the id column is an alias of the rowid.
according to your CREATE SQL it is.
Your code could be the simpler :-
public long add(EmployeeData data){
long id;
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(NAME, data.getName());
id = db.insert(TABLE_NAME, null, cv);
db.close();
return id;
}
However, it is inefficient to close the database -
close itself is not that inefficient, the inefficiency is opening the database again which is relatively expensive.
This q/a has some details regarding this Best place to close database connection
I would suggest the even simpler :-
public long add(EmployeeData data) {
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(NAME, data.getName());
return db.insert(TABLE_NAME, null, cv);
}
Example
Here's the code of an example based upon your code (using the logcat as well as the toast) :-
The DatabaseHelper DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static String DBNAME = "MYDB";
public static int DBVERSION = 1;
public static String TABLE_NAME = "mytable";
public static String ID = "_id";
public static String NAME = "_name";
public DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE "+TABLE_NAME+" ( "+ID+" INTEGER PRIMARY KEY, "+NAME+" VARCHAR2(25))";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long add(EmployeeData data) {
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(NAME, data.getName());
return db.insert(TABLE_NAME, null, cv);
}
}
The invoking Activity
the onClickListener has been replaced with direct invocation of 2 inserts
in addition to using the toast the log has been used to record the id's inserted
:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper helper=new DBHelper(MainActivity.this);
EmployeeData data=new EmployeeData(1, "TestIt");
long id=helper.add(data);
data.setId(id);
Toast.makeText(MainActivity.this, Long.toString(id), Toast.LENGTH_SHORT).show();
Log.d("ADDEMP","ID of Employee was " + id);
data.setName("TestAnother");
data.setId(id =helper.add(data));
Toast.makeText(this,Long.toString(id),Toast.LENGTH_SHORT).show();
Log.d("ADDEMP","ID of Employee was " + id);
}
}
The EmployeeData class (guessed) :-
public class EmployeeData {
long id;
String name;
int something;
EmployeeData(int something, String name) {
this.id = -1;
this.name = name;
this.something = something;
}
public long getId() {
return id;
}
public int getSomething() {
return something;
}
public String getName() {
return name;
}
public void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSomething(int something) {
this.something = something;
}
}
Results
When the above is run after ensuring that no database already exists (the App is uninstalled from the test device (Emulator) via settings)
Uninstalling the App deletes the database and should be undertaken if any changes to the schema have been made, otherwise those changes will not be applied (not entirely true as you could introduce code to make such changes).
The LogCat shows :-
D/ADDEMP: ID of Employee was 1
D/ADDEMP: ID of Employee was 2
If run a second time the LogCat shows :-
D/ADDEMP: ID of Employee was 3
D/ADDEMP: ID of Employee was 4
Additional as per comments
As per the comments you issue was that you were inadvertently using a temporary database/in_memory database and rows were being added to a new database each time and hence the id was always 1.
The following are some suggested changes (see comments in the code) based upon your GITHUB code.
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "adityya425"; //<<<<<<<<<< SUGGESTED ADDITION
public static final int DB_VERSION = 1; //<<<<<<<<<< ADDED
final String TABLE_NAME="Employee";
final String ID="_id";
final String NAME="name";
/*
<<<<<<<<<< Replaced constructor with simpler to use (only requires the Context to be passed to the helper)
public DBHelper(#Nullable Context context, #Nullable String name, #Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, null, version);
}
*/
public DBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION); //<<<<<<<<<< only context is passed
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql="CREATE TABLE "+TABLE_NAME+" ( "+ID+" INTEGER PRIMARY KEY, "+NAME+" VARCHAR2(25))";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long add(EmployeeData data){
long id;
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(NAME, data.getName());
id=db.insert(TABLE_NAME, null, cv);
//String sql="SELECT * FROM "+TABLE_NAME+" WHERE "+NAME+" = "+"'"+data.getName()+"'";
//Cursor c=db.rawQuery(sql, null);
// if (c.moveToFirst()) {
// id = c.getInt(c.getColumnIndex(ID));
// }else {
// id=-1;
// }
return id;
}
/*
<<<<<<<<<< NOT REQUIRED optional extra that will output all the existing rows to the log
e.g.
2021-03-23 18:21:01.749 4963-4963/a.a.adityya425 D/CURSORINFO: ID = 1 NAME = harry
2021-03-23 18:21:01.749 4963-4963/a.a.adityya425 D/CURSORINFO: ID = 2 NAME = bert
*/
public void showALL(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d("CURSORINFO","ID = " + csr.getLong(csr.getColumnIndex(ID)) + " NAME = " + csr.getString(csr.getColumnIndex(NAME)));
}
csr.close();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
EditText etName;
Button btnAdd;
DBHelper helper; //<<<<<<<<<< Single helper with class scope
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new DBHelper(this); //<<<<<<<< Instantiate Helper
etName=findViewById(R.id.etName);
btnAdd=findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(v -> {
//DBHelper helper=new DBHelper(MainActivity.this, "mydb", null, 1); <<<<<<<<<< REMOVED (no need)
EmployeeData data=new EmployeeData(etName.getText().toString());
long id=helper.add(data);
data.setId(id);
Toast.makeText(MainActivity.this, Long.toString(id), Toast.LENGTH_SHORT).show();
helper.showALL(MainActivity.this); //<<<<<<<<<< Optional (logcat is available longer)
});
}
}
Testing
The App was run and 3 Employees were added (Fred, Mary and Susan). The logcat shows :-
2021-03-23 18:40:15.495 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 1 NAME = Fred
2021-03-23 18:40:22.964 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 1 NAME = Fred
2021-03-23 18:40:22.964 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 2 NAME = Mary
2021-03-23 18:40:29.643 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 1 NAME = Fred
2021-03-23 18:40:29.643 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 2 NAME = Mary
2021-03-23 18:40:29.643 5642-5642/a.a.adityya425 D/CURSORINFO: ID = 3 NAME = Susan
This is the code I used in SQLlite when I needed the new auto incremented primary key:
int getId(){
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()) {
id = rs.getLong(1);
return id;
}
}
where statement is a PreparedStatement

How to Show SQLite table in Logcat

Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
public static final String Favourites = "Favourites";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL, " + Favourites + " Boolean NOT NULL);";
private static final String Show_Table = "Select * From " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void showData(SQLiteDatabase db){db.execSQL(Show_Table);}
public void insertData(String contactName, String phoneNumber,String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
values.put(DatabaseHelper.Favourites, favourites);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
public int addToFavourites(String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Favourites, favourites);
// updating row
return db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.Phone_Number + " = ?", new String[]{favourites});
}
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Modal
public class FavouritesHelper {
public String Name;
public String PhoneNumber;
public boolean Favourites;
public FavouritesHelper() {
}
public FavouritesHelper(String Name, String PhoneNumber, Boolean Favourites) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
this.Favourites = Favourites;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public boolean getFavourites() {
return Favourites;
}
public void setFavourites(boolean Favourites) {
this.Favourites = Favourites;
}
}
This is my database helper and I'm trying to fetch the table in logcat but I don't know how to do that. I know the code is Select * from <tablename> but how do i implement that. I want to see all the data in my table.
Soltion:
Please follow the following steps:
First Step:
Make the below method in DatabaseHelper class:
public List<FavouritesHelper> getAllData() {
List<FavouritesHelper> data = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + FavouritesHelper.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FavouritesHelper alldata = new FavouritesHelper();
alldata.setName(cursor.getString(cursor.getColumnIndex(FavouritesHelper.Name)));
alldata.setPhoneNumber(cursor.getString(cursor.getColumnIndex(FavouritesHelper.PhoneNumber)));
alldata.setFavourites(cursor.getBoolean(cursor.getColumnIndex(FavouritesHelper.Favourites)));
data.add(alldata);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return data;
}
Second Step:
In your activity:
declare a global object: List<FavouritesHelper> AllData inside your class.
Third Step:
then, add this AllData = new List<FavouritesHelper>(); in your onCreate()
Fourth Step:
write this in your activity after inserting data: AllData = database.getAllData();
Fifth Step:
Print it in log using below statement:
for(FavouritesHelper helper : AllData) {
Log.e("values : ", helper.getName() + ", " + helper.getPhoneNumber() + ", " + helper.getFavourites());
}
That's it.
Try it out. Hope it Helps.
As #pskink suggested you can use dumpCursor like this
create this method inside your DatabaseHelper class
public void dumpCursorInLogCat() {
//here first getting the readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(Show_Table, null);
//here is how you can Dump cursor
DatabaseUtils.dumpCursor(cursor);
cursor.close();
}
and call this method in your activity whenever you want to show data in logcat
call it inside your activity like
new DatabaseHelper(your_activity_name.this).dumpCursorInLogCat();

SQLite DataBase Read Error 'no such file or directory '

Hello I was working with SQlite on my phone with android studio
I have a simple database like this :
DATABASE 1 :
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip, String port, String rele) {
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
/* ... same for more items ...*/
long id = dbb.insert(TABLE_NAME, null, contentValues);
return id;
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.NAME, myDbHelper.IP, myDbHelper.PORT, myDbHelper.RELE, myDbHelper.Hash};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
String ipE = cursor.getString(cursor.getColumnIndex(myDbHelper.IPE));
/* ... same for more items ...*/
buffer.append("*" + cid + "-" + name + "-" + ipE + "-" + port + "-" + rele + "\n");
}
List1.colu = i;
return buffer.toString();
}
public int delete(String uid) {
SQLiteDatabase db = myhelper.getWritableDatabase();
String delgrp = "DELETE FROM " + TABLE_NAME + " WHERE _id='" + uid + "'";
db.execSQL(delgrp);
return 1;
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/* ... same for more items ...*/
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(255) ," + IPE + " VARCHAR(255) ," + TEST1 + " VARCHAR(255) ," + TEST2 + " VARCHAR(255) ," + Hash + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
}
I Wanted to add another TABLE to same database (MyDataBase)
So i created another java class named MyDbAdapter2
Same codes as above just changed class names and Table name
helper = new myDbAdapter(this);
helper2 = new myDbAdapter2(this);
DATABASE 2 :
public class myDbAdapter2 {
myDbHelper myhelper;
public myDbAdapter2(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip) {
/*...*/
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.ITEM, myDbHelper.SUBITEM};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.ITEM));
String ipe = cursor.getString(cursor.getColumnIndex(myDbHelper.SUBITEM));
buffer.append("*" + cid + "-" + name + "-" + ipe + "\n");
}
// List1.colu=i;
return buffer.toString();
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data2"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/*...*/ //Column II
// ... // Column III
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEM + " VARCHAR(255) ," + SUBITEM + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
// Message.message(context,""+e);
}
}
}
}
When i try to access the other (Data2) database it cause a error !
android.database.sqlite.SQLiteException: no such table: Data2 (Sqlite code 1): , while compiling: SELECT _id, Item, SubItem FROM Data2, (OS error - 2:No such file or directory)
I Saw this on Log :
09-13 09:31:05.788 18454-18454/com.example.discopc.yubismart I/HwSecImmHelper: mSecurityInputMethodService is null
09-13 09:31:06.468 18454-18604/com.example.discopc.yubismart E/SQLiteLog: (1)
09-13 09:31:06.571 18454-18604/com.example.discopc.yubismart I/Process: Sending signal. PID: 18454 SIG: 9
Whats the problem ? First database works fine but second one not ,
Thanks.... ?
As you said - I Wanted to add another TABLE to same database (MyDataBase)
You should not use two different class for creating two different table in sqlite database. While executing one single of your adapter classes its creating one table and if your db version is same / different in adapter classes then one of two table would not be created / would be deleted.
Here db version is same that's why second table is not creating.
Create as many as your required tables inside onCreate() of your myDbHelper class and inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) execute drop table code for each table.
When you need another new table just create table as above and write code for drop table inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion).
You just need to remember for creating new tables or any structural change inside your sqlite database would be reflected only after changing the VERSION CODE of database.
You have created a database once with name MyDataBase having table Data.
You are again trying to create same MyDataBase with table Data2 that is causing the problem.
"I Want to create only 1 database , changing name to MyDataBase2 will work but why ?"
When you are changing name to MyDataBase2 it works as this one is a completely new database and you can create the Data2 table in it.
So if you want to create Data2 in your first version of database you have to create the table Data2 in it but not a completely new data base. If you want to know more about it please find it here.
I believe this answered your question.

How to create two tables in SQLite and use the insertData for the two?

I am developing a browser and created a table to save the favorites, now I intend to create the history, I created a new table but the error, in logCat says that the table does not exist, can anyone help me?
package br.wds.yourbrowser;
import android.content.*;
import android.database.sqlite.*;
import android.support.v4.view.*;
public class DataBaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME="favoritos.db";
public static final String TABLE_NAME="favoritos";
public static final String TABLE_NAME_TWO="historicos";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="LINK";
public static final String COL_HIS_1="PAGE";
public static final String COL_HIS_2="URL";
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME+ "(" + "_ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, LINK TEXT)");
db.execSQL("CREATE TABLE " + TABLE_NAME_TWO+ "(" + "_ID INTEGER PRIMARY KEY AUTOINCREMENT, PAGE TEXT, URL TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME_TWO);
}
public boolean insertData(String name, String link, String page, String url)
{
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try{
ContentValues cv = new ContentValues();
cv.put(COL_2, name);
cv.put(COL_3, link);
final long result = db.insert(TABLE_NAME,null,cv);
ContentValues cvs = new ContentValues();
cvs.put(COL_HIS_1, page);
cvs.put(COL_HIS_2, url);
final long re = db.insert(TABLE_NAME_TWO,null,cvs);
db.setTransactionSuccessful();
db.close();
}catch(SQLiteException e){
}
finally{
db.endTransaction();
}
return false;
}
}
It could be that the method onUpgrade is dropping the tables and you are not creating them again with the new structure. So, you could either drop them and recreate onUpgrade, but will lose the data or use the sql command ALTER TABLE to add columns or whatever changes you would like. I hope this helps.

Table is not being created using SQLite in Android application

I try to create a table using sqlite in my application.
Here is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TOTAL_USAGE = "total_usage";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT,"
+ KEY_TOTAL_USAGE + " TEXT);";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// values.put(KEY_TOTAL_USAGE, total_usage); // Total_usage
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Storing user details in database
* */
public void updateUser(String email, String total_usage) {
String selectQuery = "UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(selectQuery);
db.setTransactionSuccessful();
db.close();
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
My question is: Why is table login never created? Am I doing something wrong? It couldnt be this hard to solve a problem like this. Im encountering much difficulties using Sqlite. It would be nice if someone could help me. Im using phpmyadmin as database
The application itself gives no erros, logcat is empty
And I deleted and run the application billion times, but it did not work
Maybe this information is usefull: When I type adb in terminal, it is not recognized.
why is onCreate() method never called? Forgive me If I misuse some terms as I am getting crazy by not solving this issue for 1 week :(
I used this in my code: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
The code below did not worked:
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.
What you can do is store a variable field
SQLiteDatabase db;
and then in the constructor call db = db.getWriteableDatabase()/readable();
I think this will solve your problem :)
Edit: Try this:
private SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void open(){
db = getWritableDatabase();
}
And then do something like this:
DatabaseHandler dh = new DatabaseHandler();
dh.open()
If this still doesn't work, try
https://www.google.se/?gws_rd=ssl#q=android+sqlite+oncreate+not+called
Good luck!

Categories