SQLiteException no such table - android-sqlite

just starting out on Android and I am trying to create a simple app that has an SQLite database for collecting names and contact nos. I created a view activity that will display the contents in a list view using a simpleCursorAdapter (yes its depreciated but I have yet to cover using custom adapters. Anyway, so far the code compiles just fine. Its when I click on the button to start the view activity I get an
SQLite exception: no such table: clientTable (code 1): , while compiling: SELECT _id, name, mobile FROM clientTable.
below is the code for my database class
package com.example.ideahutquizz;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ClientDatabase extends SQLiteOpenHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_MOBILE = "mobile";
public static final String DATABASE_NAME = "clientDatabase";
public static final String TABLE_NAME = "clientTable";
public static final int DATABASE_VERSION = 1;
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
+ KEY_ROWID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + "TEXT NOT NULL,"
+ KEY_MOBILE + "TEXT NOT NULL" + ")";
public ClientDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
and here is the code for the view activity
package com.example.ideahutquizz;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ViewDataActivity extends ActionBarActivity {
Button back;
ListView clientList;
SQLController clientDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
clientList = (ListView)findViewById(R.id.listView1);
back = (Button)findViewById(R.id.button1);
clientDB = new SQLController(this);
clientDB.open();
Cursor cursor = clientDB.readData();
String[] from = new String[]{ClientDatabase.KEY_ROWID, ClientDatabase.KEY_NAME, ClientDatabase.KEY_MOBILE};
int[] to = new int[]{R.id.textView_id, R.id.textView_name, R.id.textView_mobile};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_item_row, cursor, from, to);
adapter.notifyDataSetChanged();
clientList.setAdapter(adapter);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
clientDB.close();
Intent back = new Intent(ViewDataActivity.this, ControlPanel.class);
startActivity(back);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
any help is much appreciated.
updated....
I altered the create table statement as follows but I am still getting the same error...
private static final String CREATE_TABLE =
"create table " + TABLE_NAME + "("
+ KEY_ROWID + " integer primary key autoincrement,"
+ KEY_NAME + " text not null,"
+ KEY_MOBILE + " text not null" + ")";

The table isn't created:
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
Will produce this string:
String CREATE_TABLE = "create tableclientTable("
You need to add a space after the create table:
String CREATE_TABLE = "create table "
+ TABLE_NAME + "("
Same goes for the field names
So, at the end, the string will be:
String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_MOBILE + " TEXT NOT NULL" + ")";

Your CREATE TABLE statement will fail due to some missing spaces;
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
+ KEY_ROWID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + "TEXT NOT NULL,"
+ KEY_MOBILE + "TEXT NOT NULL" + ")";
...will result in something like
create tableclientTable(
_idINTEGER PRIMARY KEY AUTOINCREMENT,
nameTEXT NOT NULL,
mobileTEXT NOT NULL)
...which will cause a syntax error and not create the table.

Related

Updating single row in SQLite Android Studio

So I'm trying to update one row of my sql database with this following method
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
However, whenever the function is called, it updates all the rows. I've tried to change the values within the "update" method called but I haven't been able to make it work
There is nothing intrinsically wrong with the code that you have shown. The example below, which utilises your exact code that you have shown, works.
As such your issue is either with other unprovided code or with the method you are using to determine that no data has been updated.
For this test the following was the code for the class that is subclass of SQLiteOpenHelper, in this case ServiceDBHelper.java :-
public class ServiceDBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "service.db";
public static final int DBVERSION = 1;
public static final String TABLE_SERVICE = "service";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_RATE = "rate";
public ServiceDBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_SERVICE + "(" +
COLUMN_NAME + " TEXT PRIMARY KEY, " +
COLUMN_RATE + " TEXT" +
")";
db.execSQL(crt_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertService(String name, String price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME,name);
cv.put(COLUMN_RATE,price);
return db.insert(TABLE_SERVICE,null,cv);
}
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
public void logService(String description) {
String TAG = "LOGSERVICE";
Log.d(TAG,"Logging information for the Service Table for " + description);
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_SERVICE,null,null,null,null,null,null);
Log.d(TAG,"Number of rows in the " + TABLE_SERVICE + " table is " + String.valueOf(csr.getCount()));
while (csr.moveToNext()) {
Log.d(TAG,
"Column " + COLUMN_NAME + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_NAME)) +
". Column " + COLUMN_RATE + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_RATE))
);
}
csr.close();
}
}
As you can see the modiService method is as per you code.
Other code has been added to :-
Create the table (named service) when the database is created.
Insert rows into the table to add some test data.
Write to data from the table to the log.
The following is the code used in an Activity to
- insert some rows,
- display the rows
- update (modify a row)
- display the rows
The code used in MainActivity.java was :-
public class MainActivity extends AppCompatActivity {
ServiceDBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new ServiceDBHelper(this);
mDBHlpr.insertService("Fred","125.45");
mDBHlpr.insertService("Mary","99.75");
mDBHlpr.insertService("Harry","245.34");
mDBHlpr.logService("After initial inserts");
mDBHlpr.modiService("Mary","99.75","Susan","333.33");
mDBHlpr.logService("After Updating Mary to Susan");
}
}
The relevant output in the Log was :-
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After initial inserts
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Mary. Column rate has a value of 99.75
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After Updating Mary to Susan
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Susan. Column rate has a value of 333.33
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
As can be seen the row Mary 99.75 has been changed using the modiService method to Susan 333.33.

SQLite database is not updating within an application

I am developing an application. When I modify my data, the previous data is displayed and not the updated data. This is the ModifyActivity.java file:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText titleText, dateText, timeText;
private Button updateBtn, deleteBtn;
public Calendars calendars;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modify_record);
dbHelper = new DatabaseHelper(this);
calendars = new Calendars();
titleText = (EditText) findViewById(R.id.title_edittext_modify);
timeText = (EditText) findViewById(R.id.time_edittext_modify);
dateText = (EditText) findViewById(R.id.date_edittext_modify);
updateBtn = (Button) findViewById(R.id.btn_update);
deleteBtn = (Button) findViewById(R.id.btn_delete);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String time = intent.getStringExtra("time");
String date = intent.getStringExtra("date");
titleText.setText(title);
timeText.setText(time);
dateText.setText(date);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
titleText.setText(titleText.getText().toString() + " ");
timeText.setText(dateText.getText().toString() + " ");
dateText.setText(timeText.getText().toString() + " ");
calendars.set_remindertitle(titleText.getText().toString() + " ");
calendars.set_reminderdate(dateText.getText().toString() + " ");
calendars.set_remindertime(timeText.getText().toString() + " ");
dbHelper.update(calendars);
this.returnHome();
break;
case R.id.btn_delete:
dbHelper.delete(calendars);
this.returnHome();
break;
}
}
public void returnHome() {
Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
The database doesn't update. It shows the previous data again. This is the database class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "calendar.db";
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_REMINDER_TITLE = "_remindertitle";
public static final String COLUMN_REMINDER_DESCRIPTION = "_reminderdescription";
public static final String COLUMN_REMINDER_DATE = "_reminderdate";
public static final String COLUMN_REMINDER_TIME = "_remindertime";
public static final String COLUMN_REMINDER_REPEAT = "_reminderrepeat";
public static final String COLUMN_REMINDER_SNOOZE = "_remindersnooze";
SQLiteDatabase database;
// Database Information
Class<? extends DatabaseHelper> context = getClass();
DatabaseHelper dbHelper;
// Creating table query
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_REMINDER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_REMINDER_DATE + " TEXT, " + COLUMN_REMINDER_TIME + " TEXT, " + COLUMN_REMINDER_TITLE + " TEXT, "
+ COLUMN_REMINDER_DESCRIPTION + " TEXT, " + COLUMN_REMINDER_REPEAT + " TEXT, " + COLUMN_REMINDER_SNOOZE + " TEXT " + ");";
Log.i("Query", query);
db.execSQL(query);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
public void remove(String id) {
String string = String.valueOf(id);
SQLiteDatabase database = getReadableDatabase();
database.execSQL("DELETE FROM " + TABLE_REMINDER + " WHERE _id = '" + string + "'");
}
public void addReminder(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());
SQLiteDatabase database = getReadableDatabase();
database.insert(TABLE_REMINDER, null, contentValues);
Log.i("insData", "the data has been inseted");
database.close();
}
public Cursor fetch() {
String[] columns = new String[]{COLUMN_ID, /*COLUMN_REMINDER_DATE, COLUMN_REMINDER_TIME, COLUMN_REMINDER_TITLE,*/
COLUMN_REMINDER_DESCRIPTION, COLUMN_REMINDER_REPEAT, COLUMN_REMINDER_SNOOZE};
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query(TABLE_REMINDER, columns, null, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
return cursor;
}
public int update(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());/*
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());*/
SQLiteDatabase database = getReadableDatabase();
int i = database.update(TABLE_REMINDER, contentValues, COLUMN_ID + " = " + calendars.get_id(), null);
database.close();
return i;
}
public void delete(Calendars calendars) {
database = getReadableDatabase();
database.delete(TABLE_REMINDER, COLUMN_ID + "=" + calendars.get_id(), null);
}
}
I believe that the update button should be working fine. I am new to Android and don't know how to solve this problem. Any suggestions on how to solve it?
If you're update function returns an int, then in your onClick function, rather than typing:
dbHelper.update(calendars);
You need to type:
int update = dbHelper.update(calendars);
Or:
if (dbHelper.update(calendars) > 0) {
// do something here
}
I would recommend the latter of the options. See how you go.

SQLite app won't run at all. Force close message appears

I am creating an app using SQLite.
It crashes before loading.
I fixed all viable errors and since I do not even get a log info, I am having troubles figuring out the error.
Please help.
SQLHelper
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MediaDB";
// Media table name
private static final String TABLE_MEDIA = "media";
// Media Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TYPE = "type";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TYPE,KEY_TITLE,KEY_AUTHOR};
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create media table
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
// create media table
db.execSQL(CREATE_MEDIA_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older media table if existed
db.execSQL("DROP TABLE IF EXISTS media");
// create fresh media table
this.onCreate(db);
}
//ADD MEDIA
public void addMedia(Media media){
//for logging
Log.d("addMedia", media.toString());
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TYPE, media.getType()); // get title
values.put(KEY_TITLE, media.getTitle()); // get title
values.put(KEY_AUTHOR, media.getAuthor()); // get author
// insert
db.insert(TABLE_MEDIA, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// close
db.close();
}
//GET MEDIA
public Media getMedia(int id){
// get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// build query
Cursor cursor =
db.query(TABLE_MEDIA, // table
COLUMNS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // d. selections args
null, // group by
null, // having
null, // order by
null); // limit
// if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// build media object
Media media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
//log
Log.d("getMedia("+id+")", media.toString());
// return media
return media;
}
//GET ALL MEDIA
public List<Media> getAllMedia() {
List<Media> medias = new LinkedList<Media>();
// build the query
String query = "SELECT * FROM " + TABLE_MEDIA;
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// go over each row, build media and add it to list
Media media = null;
if (cursor.moveToFirst()) {
do {
media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
// Add media to media
medias.add(media);
} while (cursor.moveToNext());
}
Log.d("getAllMedia()", medias.toString());
// return media
return medias;
}
//UPDATE
public int updateMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("type", media.getType()); // get title
values.put("title", media.getTitle()); // get title
values.put("author", media.getAuthor()); // get author
// updating row
int i = db.update(TABLE_MEDIA, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selection args
// close
db.close();
return i;
}
//DELETE
public void deleteMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// delete
db.delete(TABLE_MEDIA, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selections args
// close
db.close();
//log
Log.d("deleteMedia", media.toString());
}
}
Media object class
public class Media {
private int id;
private String type;
private String title;
private String author;
public Media(){}
public Media(String type, String title, String author) {
super();
this.type = type;
this.title = title;
this.author = author;
}
//getters & setters
// getting ID
public int getId(){
return this.id;
}
// setting id
public void setId(int id){
this.id = id;
}
// getting type
public String getType(){
return this.type;
}
// setting title
public void setType(String type){
this.type = type;
}
// getting title
public String getTitle(){
return this.title;
}
// setting title
public void setTitle(String title){
this.title = title;
}
// getting author
public String getAuthor(){
return this.author;
}
// setting author
public void setAuthor(String author){
this.author = author;
}
#Override
public String toString() {
return "Media [id=" + id + ", type=" + type + ",title=" + title + ", author=" + author
+ "]";
}
}
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteHelper db = new MySQLiteHelper(this);
/**
* CRUD Operations
* */
// add Media
db.addMedia(new Media("Book", "Android Application Development Cookbook", "Wei Meng Lee"));
db.addMedia(new Media("Book", "Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
db.addMedia(new Media("Book", "Learn Android App Development", "Wallace Jackson"));
// get all media
List<Media> list = db.getAllMedia();
// delete one media
db.deleteMedia(list.get(0));
// get all media
db.getAllMedia();
}
}
There's an error in you table creation:
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
TYPE is not a valid SQLlite Data Type.
Please refer to this page: https://www.sqlite.org/datatype3.html
I'd write your table creation as
String CREATE_MEDIA_TABLE = "CREATE TABLE media (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TEXT, "+
"title TEXT, "+
"author TEXT)";

“Table X has no column named Y” error inserting data into a SQLite database

I got this error:
10-08 22:23:06.635: E/SQLiteLog(20613): (1) table mytable has no column named GPS
10-08 22:23:06.645: E/SQLiteDatabase(20613): Error inserting AppName=Ster-Kinekor GPS=false Time=22:23:6 Network=true Date=2014/10/08
10-08 22:23:06.645: E/SQLiteDatabase(20613): android.database.sqlite.SQLiteException: table mytable has no column named GPS (code 1): , while compiling: INSERT INTO mytable(AppName,GPS,Time,Network,Date) VALUES (?,?,?,?,?)
I have checked for all the normal silly mistakes people make to get this error, pretty sure I don't have a comma or spacing wrong. Please help me find the error, really appreciate any assistance
Here's the relevant code:
public static final String KEY_ROWID = "id";
public static final String KEY_AppName = "AppName";
public static final String KEY_Date = "Date";
public static final String KEY_Time = "Time";
public static final String KEY_Gps = "GPS";
public static final String KEY_Network = "Network";
...
...
...
public void onCreate(SQLiteDatabase arg0) {
try{
arg0.execSQL("create table if not exists mytable ("
+ "id integer primary key autoincrement, "
+ KEY_AppName+" text not null,"
+ KEY_Date+" text,"
+ KEY_Time+ " text,"
+ KEY_Gps+" text,"
+ KEY_Network+" text"
+");");
} catch (Exception e){
e.printStackTrace();
}
}
public void insertRecord(LocationUsageDB lb)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();//
initialValues.put(KEY_AppName, lb.AppName); //just do the same for any other columns
initialValues.put(KEY_Date, lb.Date);
initialValues.put(KEY_Time, lb.Time);
initialValues.put(KEY_Gps, lb.Gps);
initialValues.put(KEY_Network, lb.Network);
db.insert(TABLE_NAME, null, initialValues);
db.close();
}
And I send values here:
mydb.insertRecord(new LocationUsageDB(foregroundTaskAppName, date, t.hour+":"+t.minute+":"+t.second, "false", "true" ));

Trimming whitespace from char-type columns using MyBatis

Is there an easy way of trimming whitespace off of char-type columns when using a MyBatis XML mapper resultMap or resultType? Or do I need to write a custom type handler/add code to my JavaBean setters?
This a simple example for removing whitespace from VARCHAR column following TypeHandlers – MyBatis 3.
package com.foo.bar.mybatis.handler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
#MappedJdbcTypes(JdbcType.VARCHAR)
public class StringTrimTypeHandler extends BaseTypeHandler<String> {
#Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
System.out.println("StringSpaceTypeHandler.getNullableResult(ResultSet rs, String columnName) [rs=" + rs + ", columnName=" + columnName + "]");
return rs.getString(columnName);
}
#Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
System.out.println("StringSpaceTypeHandler.getNullableResult(ResultSet rs, int columnIndex) [rs=" + rs + ", columnIndex=" + columnIndex + "]");
return rs.getString(columnIndex);
}
#Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
System.out.println("StringSpaceTypeHandler.getNullableResult(CallableStatement cs, int columnIndex) [cs=" + cs + ", columnIndex=" + columnIndex + "]");
return cs.getString(columnIndex);
}
#Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
System.out.println("StringSpaceTypeHandler.setNonNullParameter() [ps=" + ps + ", i=" + i + ", parameter=" + parameter + ", jdbcType=" + jdbcType + "]");
parameter = parameter.trim();
ps.setString(i, parameter);
}
}
The key part is using trim() in setNonNullParameter() method to remove heading and tailing whitespace before pass it to PreparedStatement.
After creating StringTrimTypeHandler class, you need to config it in mybatis-config.xml.
<!-- mybatis-config.xml -->
<configuration>
.....
<typeHandlers>
<typeHandler handler="com.foo.bar.mybatis.handler.StringTrimTypeHandler"/>
</typeHandlers>
.....
</configuration>
You then could config logging – MyBatis 3 in MyBatis to see the actual the sql parameter.
The best way to do this is to create a type handler that will be used instead of the default StringTypeHandler. It would be handier if there was a flag on the XML, though.