I want to create a simple database for my android application in sqlite. I just want to add my values to the table.
This is my code but this is not working for me because the table is not shown at DDMS.
public class QuickSubmitContext extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "submitManager";
private static final String TABLE_CONTACTS = "submit";
private static final String KEY_ID = "id";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_DNCA = "donotca";
private static final String KEY_CA = "callagain";
private static final String KEY_NOTE = "note";
public QuickSubmitContext(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_PH_NO + " TEXT,"
+ KEY_DNCA + " TEXT," + KEY_CA + " TEXT," + KEY_NOTE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
}
Logcat
10-21 04:39:00.230: E/AndroidRuntime(835): FATAL EXCEPTION: main
10-21 04:39:00.230: E/AndroidRuntime(835): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aspeage.quikw/com.aspeage.quikw.FragmentLayout}: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Looper.loop(Looper.java:137)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invoke(Method.java:511)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-21 04:39:00.230: E/AndroidRuntime(835): at dalvik.system.NativeStart.main(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): Caused by: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at com.aspeage.quikw.FragmentLayout.onCreate(FragmentLayout.java:79)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Activity.performCreate(Activity.java:5104)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-21 04:39:00.230: E/AndroidRuntime(835): ... 11 more
10-21 04:39:07.090: I/Process(835): Sending signal. PID: 835 SIG: 9
10-21 04:39:13.050: E/Trace(866): error opening trace file: No such file or directory (2)
The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
Here are instructions. http://developer.android.com/guide/topics/data/data-storage.html#db
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");
So I'm making a soundboard app and I'm trying to implement saving sounds as notifications. The problem, however, is that the app crashes as soon as the user confirms saving as notification.
Heres what I have so far:
private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
CharSequence[] menu = new CharSequence[1];
menu[0] = "Notification";
// menu[1] = "Ringtone";
builder.setTitle("Save As...").setItems(menu,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
if (saveAsNotification(getSounds()
.get(position))) {
Toast.makeText(getActivity(),
"Saved as Notification",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
"Failed to Save Notification",
Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
});
builder.create().show();
return true;
}
};
public boolean saveAsNotification(Sound sound) {
byte[] buffer = null;
InputStream fIn = getActivity().getBaseContext().getResources()
.openRawResource(sound.getSoundResourceId());
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
String path = Environment.getExternalStorageDirectory().getPath()
+ "/media/audio/notifications/";
String filename = sound.getDescription() + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, sound.getDescription());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "soundboarder");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
getActivity().getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
return true;
}
Here's the logcat output when it crashes:
10-21 18:56:54.315: W/ResourceType(19905): No known package when getting value for resource number 0xffffffff
10-21 18:56:54.315: D/AndroidRuntime(19905): Shutting down VM
10-21 18:56:54.315: W/dalvikvm(19905): threadid=1: thread exiting with uncaught exception (group=0x41510ba8)
10-21 18:56:54.315: E/AndroidRuntime(19905): FATAL EXCEPTION: main
10-21 18:56:54.315: E/AndroidRuntime(19905): Process: com.metrico.trailerparkboyssoundboard, PID: 19905
10-21 18:56:54.315: E/AndroidRuntime(19905): android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.getValue(Resources.java:1123)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1038)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1015)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment.saveAsNotification(SoundboardFragment.java:130)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment$1$1.onClick(SoundboardFragment.java:106)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$3.run(AbsListView.java:3638)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.handleCallback(Handler.java:733)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.dispatchMessage(Handler.java:95)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Looper.loop(Looper.java:136)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invoke(Method.java:515)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-21 18:56:54.315: E/AndroidRuntime(19905): at dalvik.system.NativeStart.main(Native Method)
The dialogue box pops of fine, but as soon as I click on "save as notification", the app crashes.
I think that this part of the code causes the error
InputStream fIn = getActivity().getBaseContext().getResources().openRawResource(sound.getSoundResourceId());
The error message says you are trying to open the resource with the ID -1, make sure getSoundResourceId() returns the correct ID number.
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 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();
Anyone who follows Android tags are probably familiar with me. I am having the hardest time implementing a SQLite database for my highscores. This is also my first time working with SQLite.
I am trying to insert just two variables -- int and long. My insert() method is not working correctly. Any advice other than the stuff talked about above is also appreciated.
Thank you in advance for your help.
Highscores.java
public class Highscores extends Activity {
DatabaseHelper dh;
SQLiteDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.highscoresmain);
dh = new DatabaseHelper(this);
dh.openDB(db);
long x = 11;
int y = 22;
TextView rank = (TextView)findViewById(R.id.rank);
TextView percentage = (TextView)findViewById(R.id.percentage);
TextView score = (TextView)findViewById(R.id.score);
TextView r1r = (TextView)findViewById(R.id.r1r);
TextView r1p = (TextView)findViewById(R.id.r1p);
TextView r1s = (TextView)findViewById(R.id.r1s);
dh.insert(x, y, db); //Line 55
scores = dh.getScore(db);
percentages = dh.getPercentage(db);
rank.setText("Rank Column - TEST");
percentage.setText("Percentage Column - TEST ");
score.setText("Score Column - Test");
r1r.setText("test..rank");
r1p.setText("" + percentages);
r1s.setText("test..score");
table = (TableLayout)findViewById(R.id.tableLayout);
dh.closeDB(db);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
// Table columns names.
private static final String RANK = "_id";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
public SQLiteDatabase openDB(SQLiteDatabase db) {
db = this.getWritableDatabase();
return db;
}
public int getPercentage(SQLiteDatabase db) {
//Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + ";", null);
int i = 0;
if(c.getCount() == 0) {
i = 333;
} else if (c.getCount() == 1) {
i = 444;
} else {
i = 888;
/*c.moveToFirst();
int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
if(columnIndex != -1) {
i = c.getInt(columnIndex);
} else {
i = 999;
}*/
}
c.close();
return i;
}
//Insert new record.
public long insert(long score, int percentage, SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); //Line 120
}
public synchronized void closeDB(SQLiteDatabase db) {
if(db != null) {
db.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE + " ("
+ RANK + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SCORE + " LONG,"
+ PERCENTAGE + " INTEGER"
+ ");");
}
LogCat output
01-03 17:09:18.232: E/AndroidRuntime(1712): FATAL EXCEPTION: main
01-03 17:09:18.232: E/AndroidRuntime(1712): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.os.Looper.loop(Looper.java:137)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): at java.lang.reflect.Method.invoke(Method.java:511)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 17:09:18.232: E/AndroidRuntime(1712): at dalvik.system.NativeStart.main(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.DatabaseHelper.insert(DatabaseHelper.java:120)
01-03 17:09:18.232: E/AndroidRuntime(1712): at com.example.test.Highscores.onCreate(Highscores.java:55)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Activity.performCreate(Activity.java:5104)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 17:09:18.232: E/AndroidRuntime(1712): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 17:09:18.232: E/AndroidRuntime(1712): ... 11 more
On this line, you open the DB:
dh.openDB(db);
This stores the member variable of the database in DatabaseHelper.db (but nowhere else, and particularly not in Highscores.db). Then, you call:
dh.insert(x, y, db);
Using a null db object from Highscores. Lastly, within insert(), you use this null db object:
return db.insert(TABLE, null, values);
What you should do instead is use the following as your insert() method:
public long insert(long score, int percentage) { // Remove db parameter
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); // This will use the member variable
}
Then, call dh.insert(x, y); instead.
You should also change openDB(SQLiteDatabase db) to openDB() so that it is writing the correct DB; as it stands, it just overwrites the local variable's value (which changes nothing once the function's scope is done).
Instead of
dh.openDB(db);
say
db = dh.openDB(db);
(although the openDB method really doesn't need to have an argument). Your call to openDB doesn't store the database object reference in db, so it's NULL when you get around to calling dh.insert(..., db);.