Database Operations On Thread - java

I am working on android application which stores some data in database when the user starts the application it fetches data from the database to an ArrayList and keeps that ArrayList throughout the application life cycle. whenever I require an update to data I updates both database and ArrayList which holds the data, this approach reduces the CPU effort. here I have to update the database via a non ui thread, so that I need some suggestions,
1- is this a good approach ?
2- I have a database helper class which directly interacts with the database, and I am maintaining separate class for each tables, that communicates with the UI and Database helper class, so where should I implement thread , either in the Helper class or in the table corresponding class ?
code
DbHandler
#Override
public void onCreate(SQLiteDatabase db) {
FirstTable.createDatabaseTable(db);
SecondTable.createDatabaseTable(db);
}
public void insertData(String tableName, ContentValues contentValues) {
SQLiteDatabase db = getWritableDatabase();
db.insert(tableName, null, contentValues);
dbClose();
}
public Cursor readData(String tableName, String[] columns, String selection, String[]
selectionArgs, String groupBy, String having, String orderBy, String limit) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
return cursor;
}
public void deleteData(String tableName, String id, NewsItem newsItem) {
SQLiteDatabase db = getWritableDatabase();
db.delete(tableName, id + " =?", new String[]{String.valueOf(newsItem.getmGuid())});
dbClose();
}
public void updateData(String tableName, ContentValues contentValues, String where, String[] whereArgs) {
SQLiteDatabase db = getWritableDatabase();
db.update(tableName, contentValues, where, whereArgs);
dbClose();
}
public void dbClose() {
if (mDbHandler != null) {
mDbHandler.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
FirstTable.deleteTable(db);
SecondTable.deleteTable(db);
onCreate(db);
}
Table Specific class
public static void createDatabaseTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public static void deleteTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void createData(Data data) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_TITLE, data.getTitle());
contentValues.put(COLUMN_LINK, data.getLink());
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.insertData(TABLE_NAME, contentValues);
}
public ArrayList<NewsItem> readData() {
ArrayList<Data> allData = new ArrayList<>();
DbHandler dbHandler = DbHandler.getInstance(mContext);
Cursor cursor = dbHandler.readData(TABLE_NAME, null, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setTitle(cursor.getString(2));
data.setLink(cursor.getString(3));
allNewsList.add(newsItem);
} while (cursor.moveToNext());
}
return allData;
}
public void deleteData(Data data) {
DbHandler dbHandler = DbHandler.getInstance(mContext);
dbHandler.deleteData(TABLE_NAME, ID, data);
}
suggest me good method

Yes its good idea to store data and maintain in background process. I like to suggest you that to make a common class to handle Database & Tables.
For example
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 = "demo_database";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
private static final String TABLE_PROINFO = "proinfo";
private static final String TABLE_RETAPROINFO = "retaproinfo";
private static final String TABLE_ATTENDANCE = "attendance";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_STUDID = "studid";
private static final String KEY_AVAILABILITY = "availability";
private final ArrayList<Bean_attendance> att_list = new ArrayList<Bean_attendance>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
SQLiteDatabase db;
Cursor cursor;
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_NAME_TABLE = "CREATE TABLE " + TABLE_ATTENDANCE
+ "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STUDID + " TEXT,"
+ KEY_AVAILABILITY + " TEXT" + ")";
db.execSQL(CREATE_CATEGORY_NAME_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion) {
switch (upgradeTo) {
case 1:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 2:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 3:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 4:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 5:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 6:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 7:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 8:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 9:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 10:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 11:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
case 12:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);
break;
}
upgradeTo++;
}
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public void Add_Attandance(Bean_attendance contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STUDID, contact.getStud_id());
values.put(KEY_AVAILABILITY, contact.getAvailability());
// Inserting Row
db.insert(TABLE_ATTENDANCE, null, values);
db.close(); // Closing database connection
}
public ArrayList<Bean_attendance> Get_Attandance() {
try {
att_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANCE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean_attendance contact = new Bean_attendance();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setStud_id(cursor.getString(1));
contact.setAvailability(cursor.getString(2));
// Adding contact to list
att_list.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return att_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_attandance", "" + e);
}
return att_list;
}
public int Update_MainAttandnce(String availble,int id) {
String countQuery = "UPDATE " + TABLE_ATTENDANCE + " SET " + KEY_AVAILABILITY
+ " = " + "\"" + availble + "\"" + " where " + KEY_ID + "=" + "\"" + id
+ "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public void Delete_Attandance_main(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ATTENDANCE, KEY_ID + "=" + id, null);
db.close();
}
public void Attandanceremove() {
SQLiteDatabase db = this.getWritableDatabase();
// context.deleteDatabase(DATABASE_NAME);
db.execSQL("delete from " + TABLE_ATTENDANCE);
// db.delete(DATABASE_TABLE, null, null);
}
}

Related

SQLite Database Error - No column named task

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

Interchange ids of android database

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

Android SQLite Table Creation Error

I have my code to create SQLite database, the code create database but does not create any table. I went through some of the similar errors that others had before, I couldn't find any error. Could anyone help me.
Here is my code
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "swahilComm.db";
public static final String COUNTRY_TABLE = "countries";
public static final String COUNTRY_ID = "id";
public static final String COUNTRY_NAME = "country";
public static final String PROVINCE_TABLE = "province";
public static final String PROVINCE_ID = "id";
public static final String PROVINCE_NAME = "province";
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operation", "Database Created...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
db.execSQL(CREATE_COUNTRY_TABLE);
Log.d("Database Operation", "Tables Created...");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
db.execSQL("DROP TABLE IF EXISTS " + PROVINCE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTRY_TABLE);
// Create tables again
onCreate(db);
}
//Delete all data in the table
public void DeleteCountry() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COUNTRY_TABLE, null, null);
db.close(); // Closing database connection
}
//Delete all data in the Province table
public void DeleteProvice() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PROVINCE_TABLE, null, null);
db.close(); // Closing database connection
}
//Insert country records
public int insertCountry(Country country) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_ID, country.getId());
values.put(COUNTRY_NAME, country.getCountry());
// Inserting Row
long country_Id = db.insert(COUNTRY_TABLE, null, values);
db.close(); // Closing database connection
return (int) country_Id;
}
//Insert province records
public int insertProvince(Province province) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PROVINCE_ID, province.getId());
values.put(PROVINCE_NAME, province.getProvince());
// Inserting Row
long province_Id = db.insert(PROVINCE_NAME, null, values);
db.close(); // Closing database connection
return (int) province_Id;
}
//Retrieve all records and populate into List<Country>
//This method allow you to retrieve more fields/information into List.
public List<Country> getAllCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<Country> countryList = new ArrayList<Country>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(cursor.getString(cursor.getColumnIndex(COUNTRY_ID)));
country.setCountry(cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
countryList.add(country);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<Province>
//This method allow you to retrieve more fields/information into List.
public List<Province> getAll() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<Province> provinceList = new ArrayList<Province>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getString(cursor.getColumnIndex(PROVINCE_ID)));
province.setProvince(cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
provinceList.add(province);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
//Retrieve all records and populate into List<String>
public List<String> getAllStringCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<String> countryList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
countryList.add(i,cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<String>
public List<String> getAll_Simple() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<String> provinceList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
provinceList.add(i,cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
}
This is the the Activity Class
public class Register extends AppCompatActivity {
DBHelper repo = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
countries = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, countries);
autoCompleteTextView.setAdapter(adapter);
insertDummyData();
loadProvince_Simple();
}
// This class insert data
private void insertDummyData(){
repo.DeleteProvice();
int i = 1;
String[] provinces = {"Prince Edward Island", "Quebec", "Saskatchewan", "Yukon","Northwest Territories", "Ontario", "Nunavut", "Nova Scotia", "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador"};
for(int j=0; j < provinces.length; j++) {
Province province = new Province();
province.setId(Integer.toString(i));
province.setProvince(provinces[j]);
repo.insertProvince(province);
i++;
}
}
//This is the arrayadapter binding method as you can see
private void loadProvince_Simple(){
ArrayAdapter<String> spinnerAdapter;
DBHelper db = new DBHelper(getApplicationContext());
List<String> provinces = db.getAll_Simple();
spinnerAdapter = new ArrayAdapter<String>(Register.this,
android.R.layout.simple_spinner_item, provinces);
prov_spinner.setAdapter(spinnerAdapter);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
Read my comments below:
// TRY TO REMOVE THE SPACE BETWEEN "TEXT" TO THE "(" IN THE LAST LINE OF BOTH STRINGS
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
// YOU WROTE "INTEGET"
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";

Dumping android SQLite text content into textView

I built an app that so far manages to ADD text to a database (cannot verify yet but I killed the FC). However, when I try to read from the database it FCs because I'm unsure of how to use the Cursor object. I read the documentation and it confuses me more. I have a database with table "records" and a single column "texts". While my project manages to input text into the database (via an EditText), I'm trying unsuccessfully to return all the database entries from this "texts" column into a textView.
DB Helper inner-class:
private class dbHelper extends SQLiteOpenHelper {
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("create statement"+SQL_CREATE_ENTRIES);
try
{
db.execSQL(SQL_CREATE_ENTRIES);
}catch(SQLiteException sql)
{
sql.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS records");
onCreate(db);
}
public void addRecord(String t) {
ContentValues values = new ContentValues(1);
values.put(RECORDS_COLUMN_TEXTS,t);
getWritableDatabase().insert(TABLE_NAME, RECORDS_COLUMN_TEXTS, values);
}
public Cursor getRecords() {
return getWritableDatabase().rawQuery("select * from " + TABLE_NAME, null);
}
}
Within main class:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "CSCI598";
private static final String TABLE_NAME = "records";
public static final String RECORDS_COLUMN_TEXTS = "texts";
private dbHelper openHelper;
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
openHelper = new dbHelper(this);
switch(v.getId()) {
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
cursor.moveToFirst();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString());
break;
case R.id.append1:
String txt=et.getText().toString();
openHelper.addRecord(txt);
break;
}
logcat: http://pastebin.com/mqUn6g7P
As you can see, I'm probably trying something very stupid with the action for clicking the fetch button, ie. "openHelper.getRecords().toString()" attempting to convert all that Cursor returns to string. How can I go about this alternately in the simplest fashion?
Ok First you have get the strings from the Cursor by doing this
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
Then you can set it to the textView
tv.setText(sb.toString);
This should work actually
.Replace this part of your code
case R.id.fetch1:
tv.setText(openHelper.getRecords().toString());
break;
With this
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString);
break;
Also remove autoincrement for Text when you create the table
Replace this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
With this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT" + ")";
Also Add table name in the constructor instead of database name. Change this:
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
To this:
public dbHelper(Context context) {
super(context, TABLE_NAME, null, DATABASE_VERSION);
}

How to insert data in SQLite db in Android?

I'm implementing SQLite db in my android application i want retrieve data from JSON and store in into SQLite db .I saw one of the example of using SQLite but I'm using different column name wchi is store into SQLite db .
But when i run the app I'm getting Error like =
((1) table contacts has no column named cost ,
Error inserting phone_number=9533333333 cost=46456 name=Karthik ,
android.database.sqlite.SQLiteException: table contacts has no column named cost (code 1): , while compiling: INSERT INTO contacts(phone_number,cost,name) VALUES (?,?,?))
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 = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_COST = "cost";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_COST + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_COST, contact._cost); // Contact Phone
values.put(KEY_PH_NO, contact._mobile); //Contact phone no
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_COST, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.set_id(Integer.parseInt(cursor.getString(0)));
contact.set_name(cursor.getString(1));
contact.set_cost(cursor.getString(2));
contact.set_mobile(cursor.getString(3));
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.get_name());
values.put(KEY_COST, contact.get_cost());
values.put(KEY_PH_NO, contact.get_mobile());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Change this line
private static final int DATABASE_VERSION = 1;
to this
private static final int DATABASE_VERSION = 2;
And check your work again.
Try clear your app data then rerun the app, you may have had a different column before and run the app once (meaning the create table would not be called again).

Categories

Resources