I want to save and display the created date for an sql entry. But my app keeps crashing with this code.
Any help would be appreciated!
Here is the Save State Method for saving the note:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor;
String date=(DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE ));
//String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
if(title != null && !title.isEmpty() || body != null && !body.isEmpty()){
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color, date);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color, date);
}
}
And here is the Database adapter:
public class NotesDbAdapter {
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
public static final String KEY_COLOR = "color";
public static final String KEY_DATE = "date";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null, color text not null, date text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 4;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String title, String body, String color, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_COLOR, color);
initialValues.put(KEY_DATE, date);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_COLOR, KEY_DATE}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY, KEY_COLOR, KEY_DATE}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String title, String body, String color, String date) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
args.put(KEY_COLOR, color);
args.put(KEY_DATE, date);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
UPDATE
Okay after running it, this was the error log i got:
08-03 16:15:52.816: I/Process(29938): Sending signal. PID: 29938 SIG: 9
08-03 16:15:53.046: E/SQLiteLog(30048): (1) no such column: date
08-03 16:15:53.046: D/AndroidRuntime(30048): Shutting down VM
08-03 16:15:53.046: W/dalvikvm(30048): threadid=1: thread exiting with uncaught exception (group=0x40d23a08)
08-03 16:15:53.056: E/AndroidRuntime(30048): FATAL EXCEPTION: main
08-03 16:15:53.056: E/AndroidRuntime(30048): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.demo.notepad2/com.android.demo.notepad2.Notepadv2}: android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT _id, title, body, color, date FROM notes
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.access$600(ActivityThread.java:156)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1250)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.os.Looper.loop(Looper.java:137)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.main(ActivityThread.java:5234)
08-03 16:15:53.056: E/AndroidRuntime(30048): at java.lang.reflect.Method.invokeNative(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): at java.lang.reflect.Method.invoke(Method.java:525)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
08-03 16:15:53.056: E/AndroidRuntime(30048): at dalvik.system.NativeStart.main(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): Caused by: android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT _id, title, body, color, date FROM notes
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.NotesDbAdapter.fetchAllNotes(NotesDbAdapter.java:134)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.Notepadv2.fillData(Notepadv2.java:64)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.Notepadv2.onCreate(Notepadv2.java:58)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.Activity.performCreate(Activity.java:5108)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
08-03 16:15:53.056: E/AndroidRuntime(30048): ... 11 more
Error is in your query: change date (and _id too) with another name; usually date is a reserved keyword.
I would have put this in the comment, but my rep is not high enough.
I am pretty sure that there is a way to make the SQL table automatically put the current date and time whenever a new entry is created. Perhaps you could try that? It's been a while since I have worked with SQL though so I might be wrong.
Related
I am trying to add database in my app.I wrote this class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "testDb";
private static final String TABLE_KISILER = "loginCre";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "username";
private static final String KEY_PASS = "password";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Database Oluşturma işlemi.
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_KISILER_TABLE = "CREATE TABLE " + TABLE_KISILER + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " VARCHAR(50),"
+ KEY_PASS + " VARCHAR(50)" + ")";
db.execSQL(CREATE_KISILER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_KISILER);
onCreate(db);
}
//CRUD
// Yeni Kayıt Eklemek.
public void addLoginInfo(String username,String password) {
/*
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, username); // Kisi Adı Getir
values.put(KEY_PASS, password); // Kisi Soyadı Getir
// Ekleme işlemi...
db.insert(TABLE_KISILER, null, values);
db.close(); // Açık olan database i kapat.
*/
}
}
I want to access addLoginInfo method from main activity then I used this lines in onCreate
private DatabaseHandler _db;
_db.addLoginInfo("test", "test");
But I app is crashing.There is the logcat:
12-05 11:24:55.802: E/AndroidRuntime(2841): FATAL EXCEPTION: main
12-05 11:24:55.802: E/AndroidRuntime(2841): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.impact.xxx/com.impact.xxx.MainActivity}: java.lang.NullPointerException
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Looper.loop(Looper.java:137)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invoke(Method.java:525)
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-05 11:24:55.802: E/AndroidRuntime(2841): at dalvik.system.NativeStart.main(Native Method)
12-05 11:24:55.802: E/AndroidRuntime(2841): Caused by: java.lang.NullPointerException
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.impact.xxx.MainActivity.onCreate(MainActivity.java:164)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Activity.performCreate(Activity.java:5133)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-05 11:24:55.802: E/AndroidRuntime(2841): ... 11 more
Why I am getting nullPointerException ?
you are not initializing _db object.try this :
private DatabaseHandler _db = new DatabaseHandler(this);
_db.addLoginInfo("test", "test");
In your activity put these lines, i hope it will work
DatabaseHandler _db = new DatabaseHandler(this);
_db.getWritableDatabase();
_db.addLoginInfo("test", "test");
I am inserting the data from data base using sqlite but I am getting an error .Here is my code and error.I just enter one entry and want to display that entry ?
package com.example.database_example;
public class Information {
String name;
public Information(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Data Base.java class
package com.example.database_example;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Information inf=new Information("naveen");
DataBaseExample dbx=new DataBaseExample(MainActivity.this);
if(dbx.insertname(inf)){
Log.v("checkdbx.insertname(inf);", "save ok.");
}else{
Log.v("checkdbx.insertname(inf);", "save failed.");
}
}
}
package com.example.database_example;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseExample extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "information";
// Contacts table name
private static final String TABLE_Name= "Name";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public DataBaseExample(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name);
// Create tables again
onCreate(db);
}
public boolean insertname(Information information) {
boolean createSuccessful = false;
ContentValues values = new ContentValues();
// values.put(KEY_ID, information.getId());
values.put(KEY_NAME, information.getName());
SQLiteDatabase db = this.getWritableDatabase();
createSuccessful = db.insert(TABLE_Name, null, values) > 0;
db.close();
return createSuccessful;
}
}
Here is my error
09-24 07:25:07.138: I/Database(392): sqlite returned: error code = 1, msg = near ")": syntax error
09-24 07:25:07.138: E/Database(392): Failure 1 (near ")": syntax error) on 0x2a7080 when preparing 'CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)'.
09-24 07:25:07.148: D/AndroidRuntime(392): Shutting down VM
09-24 07:25:07.148: W/dalvikvm(392): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-24 07:25:07.158: E/AndroidRuntime(392): FATAL EXCEPTION: main
09-24 07:25:07.158: E/AndroidRuntime(392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database_example/com.example.database_example.MainActivity}: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Looper.loop(Looper.java:123)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invoke(Method.java:507)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-24 07:25:07.158: E/AndroidRuntime(392): at dalvik.system.NativeStart.main(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): Caused by: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.onCreate(DataBaseExample.java:34)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.insertname(DataBaseExample.java:55)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.MainActivity.onCreate(MainActivity.java:18)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-24 07:25:07.158: E/AndroidRuntime(392): ... 11 more
Change
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
to
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT"
+ ")";
removing the comma after TEXT
EDIT
To read all the values from the database, you can add the following method to your class DataBaseExample:
private List<Information> getAllItems()
List<Information> itemsList = new ArrayList<Information>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(TABLE_Name, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
Information c = new Information();
c.setName(cursor.getString(KEY_NAME));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}
I'm trying to code a simple randomizer app. I had the randomizer button working, but then I changed some code (which I thought was irrelevant to the randomizer button) and it started crashing and getting the "IllegalStateException: Could not execute method of the activity" error. From what I can tell, this error is very specific to what the code is, because I could not find any answers that fit my code.
package com.example.randomgamechooser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void chooseGame (View view) {
GameList dbUtil = new GameList(this);
dbUtil.open();
String string = dbUtil.getRandomEntry();
//TextView textView = new TextView(this);
TextView textView = (TextView) findViewById(R.id.chosenbox);
textView.setTextSize(40);
textView.setText(string);
//setContentView (textView);
dbUtil.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
//starts the Game Selection activity
public void openGames (View view) {
Intent intent = new Intent(this, GameSelction.class);
startActivity(intent);
}
}
And this is the referenced GameList class
package com.example.randomgamechooser;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Random;
public class GameList {
private static final String TAG = "GameList";
//database name
private static final String DATABASE_NAME = "game_list";
//database version
private static final int DATABASE_VERSION = 1;
//table name
private static final String DATABASE_TABLE = "game_list";
//table columns
public static final String KEY_NAME = "name";
public static final String KEY_GENRE = "genre";
public static final String KEY_ROWID = "_id";
//database creation sql statement
private static final String CREATE_GAME_TABLE =
"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME +" text not null, " + KEY_GENRE + " text not null);";
//Context
private final Context mCtx;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
//Inner private class. Database Helper class for creating and updating database.
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// onCreate method is called for the 1st time when database doesn't exists.
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_GAME_TABLE);
db.execSQL(CREATE_GAME_TABLE);
}
//onUpgrade method is called when database version changes.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
}
//Constructor - takes the context to allow the database to be opened/created
//#param ctx the Context within which to work
public GameList(Context ctx) {
this.mCtx = ctx;
}
//This method is used for creating/opening connection
//#return instance of GameList
//#throws SQLException
public GameList open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
//This method is used for closing the connection.
public void close() {
mDbHelper.close();
}
//This method is used to create/insert new game.
//#param name
// #param genre
// #return long
public long createGame(String name, String genre) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_GENRE, genre);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
// This method will delete game.
// #param rowId
// #return boolean
public static boolean deleteGame(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// This method will return Cursor holding all the games.
// #return Cursor
public Cursor fetchAllGames() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_GENRE}, null, null, null, null, null);
}
// This method will return Cursor holding the specific game.
// #param id
// #return Cursor
// #throws SQLException
public Cursor fetchGame(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_GENRE}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public int getAllEntries()
{
Cursor cursor = mDb.rawQuery(
"SELECT COUNT(name) FROM game_list", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
//id = getAllEntries();
Random random = new Random();
int rand = random.nextInt(getAllEntries());
if(rand == 0)
++rand;
Cursor cursor = mDb.rawQuery(
"SELECT name FROM game_list WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
// This method will update game.
// #param id
// #param name
// #param standard
// #return boolean
public boolean updateGame(int id, String name, String standard) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_GENRE, standard);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
and here is the error log
07-31 14:50:45.215: D/AndroidRuntime(280): Shutting down VM
07-31 14:50:45.215: W/dalvikvm(280): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-31 14:50:45.236: E/AndroidRuntime(280): FATAL EXCEPTION: main
07-31 14:50:45.236: E/AndroidRuntime(280): java.lang.IllegalStateException: Could not execute method of the activity
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2072)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-31 14:50:45.236: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: java.lang.reflect.InvocationTargetException
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.MainScreen.chooseGame(MainScreen.java:23)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2067)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 11 more
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Read the stacktrace carefuly. Answer is at the last "Caused by" exception;
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Query in method getRandomEntry() returns empty result, while you read from the first position.
I've been following This guide for implementing a database in an android project.
This is the code for my DBAdapter class:
package com.sab.namespace;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PROPERTYID = "propertyid";
public static final String KEY_ADDRESS = "propertyaddress";
public static final String KEY_JOBNO = "jobnumber";
public static final String KEY_ASSIGNED = "assignedto";
public static final String KEY_COMPANY = "company";
public static final String KEY_DATE = "datecreated";
public static final String KEY_MASTERKEY = "usemasterkey";
public static final String KEY_PHONEBEFORE = "phonebefore";
public static final String KEY_PROBLEM = "descriptionofproblem";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "SABDatabase";
private static final String DATABASE_TABLE = "jobs";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table jobs (_id integer primary key autoincrement, "
+ "propertyid text not null, propertyaddress text not null, "
+ "jobnumber text not null, assignedto text not null, "
+ "company text not null, datecreated text not null, "
+ "usemasterkey text not null, phonebefore text not null, "
+ "descriptionofproblem text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS jobs");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a job into the database---
public long insertJob(String propertyid, String propertyaddress, String jobnumber,
String assignedto, String company, String datecreated, String usemasterkey,
String phonebefore, String descriptionofproblem)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PROPERTYID, propertyid);
initialValues.put(KEY_ADDRESS, propertyaddress);
initialValues.put(KEY_JOBNO, jobnumber);
initialValues.put(KEY_ASSIGNED, assignedto);
initialValues.put(KEY_COMPANY, company);
initialValues.put(KEY_DATE, datecreated);
initialValues.put(KEY_MASTERKEY, usemasterkey);
initialValues.put(KEY_PHONEBEFORE, phonebefore);
initialValues.put(KEY_PROBLEM, descriptionofproblem);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular job---
public boolean deleteJob(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the jobs---
public Cursor getAllJobs()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_PROPERTYID,
KEY_ADDRESS,
KEY_JOBNO,
KEY_ASSIGNED,
KEY_COMPANY,
KEY_DATE,
KEY_MASTERKEY,
KEY_PHONEBEFORE,
KEY_PROBLEM},
null,
null,
null,
null,
null);
}
//---retrieves a particular job---
public Cursor getJob(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_PROPERTYID,
KEY_ADDRESS,
KEY_JOBNO,
KEY_ASSIGNED,
KEY_COMPANY,
KEY_DATE,
KEY_MASTERKEY,
KEY_PHONEBEFORE,
KEY_PROBLEM},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a job---
public boolean updateJob(long rowId, String propertyid, String propertyaddress, String jobnumber,
String assignedto, String company, String datecreated, String usemasterkey,
String phonebefore, String descriptionofproblem)
{
ContentValues args = new ContentValues();
args.put(KEY_PROPERTYID, propertyid);
args.put(KEY_ADDRESS, propertyaddress);
args.put(KEY_JOBNO, jobnumber);
args.put(KEY_ASSIGNED, assignedto);
args.put(KEY_COMPANY, company);
args.put(KEY_DATE, datecreated);
args.put(KEY_MASTERKEY, usemasterkey);
args.put(KEY_PHONEBEFORE, phonebefore);
args.put(KEY_PROBLEM, descriptionofproblem);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
And then I try to use the database in my ViewJobs.java class
DBAdapter db = new DBAdapter(this);
db.open();
long id;
id = db.insertJob(
"PROP121",
"MARK ANDREWS DRIVE",
"JOB32",
"COLIN",
"SAB",
"12/4/13",
"yes",
"yes",
"SHIT IS EVERYWHERE");
id = db.insertJob(
"PROP122",
"FAULTY CLOSE",
"JOB33",
"DAVE",
"SAB",
"13/4/13",
"yes",
"yes",
"FIX PLEASE");
db.close();
Toast.makeText(this, Long.toString(id), Toast.LENGTH_LONG).show();
Toast outputs -1 which tells me there has been an error with inputting the data but I can't find where I've gone wrong.
If I just ignore the error and continue on with the following code then my application crashes.
db.open();
Cursor c = db.getAllJobs();
db.close();
I would be very grateful if anyone could offer any advice!
-Harry
Here is the logcat code for when it crashes:
03-04 18:37:59.760: W/dalvikvm(2078): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
03-04 18:37:59.809: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:37:59.958: E/AndroidRuntime(2078): FATAL EXCEPTION: main
03-04 18:37:59.958: E/AndroidRuntime(2078): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sab.namespace/com.sab.namespace.ViewJobs}: android.database.sqlite.SQLiteException: no such table: jobs: , while compiling: SELECT _id, propertyid, propertyaddress, jobnumber, assignedto, company, datecreated, usemasterkey, phonebefore, descriptionofproblem FROM jobs
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.os.Looper.loop(Looper.java:137)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.main(ActivityThread.java:4424)
03-04 18:37:59.958: E/AndroidRuntime(2078): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-04 18:37:59.958: E/AndroidRuntime(2078): at dalvik.system.NativeStart.main(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): Caused by: android.database.sqlite.SQLiteException: no such table: jobs: , while compiling: SELECT _id, propertyid, propertyaddress, jobnumber, assignedto, company, datecreated, usemasterkey, phonebefore, descriptionofproblem FROM jobs
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1449)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1405)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1485)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.sab.namespace.DBAdapter.getAllJobs(DBAdapter.java:114)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.sab.namespace.ViewJobs.onCreate(ViewJobs.java:52)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.Activity.performCreate(Activity.java:4465)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-04 18:37:59.958: E/AndroidRuntime(2078): ... 11 more
03-04 18:37:59.969: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:00.328: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:38:00.358: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:00.658: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:38:00.799: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:03.210: I/Process(2078): Sending signal. PID: 2078 SIG: 9
Here is the full code for ViewJobs.java
package com.sab.namespace;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ViewJobs extends Activity {
String titles[] = {"hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe"};
ListView vListView;
ArrayAdapter<String> lVAAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
//database stuff
DBAdapter db = new DBAdapter(this);
db.open();
long id;
id = db.insertJob(
"PROP121",
"MARK ANDREWS DRIVE",
"JOB32",
"COLIN",
"SAB",
"12/4/13",
"yes",
"yes",
"SHIT IS EVERYWHERE");
id = db.insertJob(
"PROP122",
"FAULTY CLOSE",
"JOB33",
"DAVE",
"SAB",
"13/4/13",
"yes",
"yes",
"FIX PLEASE");
db.close();
Toast.makeText(this, Long.toString(id), Toast.LENGTH_LONG).show();
db.open();
Cursor c = db.getAllJobs();
db.close();
/*
if (c.moveToFirst())
{
do {
DisplayJob(c);
} while (c.moveToNext());
}
db.close();
*/
//create list
vListView = (ListView) findViewById(R.id.vlistview);
lVAAdapter = new ArrayAdapter<String>(ViewJobs.this,
android.R.layout.simple_list_item_1, titles);
//create listener
vListView.setAdapter(lVAAdapter);
vListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> lVAAdapter, View myView,
int myItemInt, long mylng) {
String selectedFromList = (String) (vListView.getItemAtPosition(myItemInt));
if (titles[myItemInt] == "hello") {
titles[2] = "test";
vListView.invalidateViews();
}
}
});
}
public void DisplayJob(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"propertyid: " + c.getString(1) + "\n" +
"propertyaddress: " + c.getString(2) + "\n" +
"jobnumber: " + c.getString(3) + "\n" +
"assignedto: " + c.getString(4) + "\n" +
"company: " + c.getString(5) + "\n" +
"datecreated: " + c.getString(6) + "\n" +
"usemasterkey: " + c.getString(7) + "\n" +
"phonebefore: " + c.getString(8) + "\n" +
"descriptionofproblem: " + c.getString(9),
Toast.LENGTH_LONG).show();
}
}
You probably added the jobs table after creating the database. The onCreate would not be called. So you need to clear the data for the onCreate to be called again.
i have a problem with my SQLite class. In fact, i was learning how to setting up (update and read) a database on android and I successfully wrote on the database, but when i try to read the informations and display them on the screen, my application just crashes.
I searched the problem and found that the cause of the crash is the Cursor. I commented the cursor's method, so if someone can help me with that, i would be thankful.
This my Database class.
package com.example.sqlprogramming;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "person_name";
public static final String KEY_RATE = "person_rate";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 2;
private Dhelper ourHelperdb;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class Dhelper extends SQLiteOpenHelper{
public Dhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + "VARCHAR NOT NULL, " +
KEY_RATE + "VARCHAR NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseClass(Context c){
ourContext = c;
}
public DatabaseClass open() throws SQLException{
ourHelperdb = new Dhelper(ourContext);
ourDatabase = ourHelperdb.getWritableDatabase();
return this;
}
public void close(){
ourHelperdb.close();
}
public long addEntry(String personName, String personHotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, personName);
cv.put(KEY_RATE, personHotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
//HERE IS MY PROBLEM WITH THE CURSOR
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_RATE};
String result = "hello";
Cursor c = ourDatabase.query(true, DATABASE_TABLE, columns, null, null, null, null, null, null);
int iRowId = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(KEY_RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRowId) + " " + c.getString(iName) +" " + c.getString(iRate) + "\n";
}
c.close();
return result;
}
}
And this Class call the Database Class and should take informations from database to display it on the screen.
package com.example.sqlprogramming;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sqlview);
TextView textInfo = (TextView) findViewById (R.id.tvSQLinfo);
DatabaseClass info = new DatabaseClass(this);
info.open();
String _data = info.getData();
info.close();
textInfo.setText(_data);
}
}
Thank you again.
I'll post stacktrace and logcat soon.
Here is my Logcat/Stacktrace
02-24 20:08:12.378: E/Curosr!(1221): I got an error here :
02-24 20:08:12.378: E/Curosr!(1221): android.database.sqlite.SQLiteException: no such column: person_name (code 1): , while compiling: SELECT _id AS _id, person_name, person_rate FROM peopleTable
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.DatabaseClass.getData(DatabaseClass.java:75)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.SQLview.onCreate(SQLview.java:14)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Activity.performCreate(Activity.java:5104)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Looper.loop(Looper.java:137)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 20:08:12.378: E/Curosr!(1221): at dalvik.system.NativeStart.main(Native Method)
Your create statement is missing a few spaces. Try using:
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " VARCHAR NOT NULL, " +
KEY_RATE + " VARCHAR NOT NULL);");
According to your current statement, your last two column names become person_nameVARCHAR and person_rateVARCHAR
If you're reading, you need to use:
ourDatabase = ourHelperdb.getReadableDatabase();
When you open your DB, you are setting it to write.
(That's my first guess, post stack trace).
Here's a working example from some of my code on how to read a cursor:
mDb = mDbHelper.getReadableDatabase();
Cursor c = mDb.query("Timesheets", new String[] {
KEY_TIMESHEETS_ROWID + " AS _id", KEY_TIMESHEETS_DESCRIPTION,
KEY_TIMESHEETS_TITLE, KEY_TIMESHEETS_DATE_START,
KEY_TIMESHEETS_DATE_END, KEY_TIMESHEETS_INVOICED,
KEY_TIMESHEETS_PROJECTID }, "timesheet_id = ?",
new String[] { String.valueOf(timesheetId) }, null, null, null);
c.moveToFirst();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timesheet timesheet = new Timesheet();
while (c.isAfterLast() == false) {
timesheet.setTimesheetId(c.getInt(0));
// ...
c.moveToNext();
}
c.close();