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.
Related
I want to add word from the insert.java class to the database translate.sql in the assets folder, but when i click the button for insert.java in the emulator it keeps shutdown unexpectedly.
I already search and trying to resolve this but seems it keep coming.
So i need help to identify the error in the code or some misspelling name from the database or others..
this is the class for insert.java
package com.han;
import android.app.Activity;
//import android.app.AlertDialog;
//import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Insert extends Activity {
public Button search, add, back;
public EditText indo;
public EditText tora;
public Cursor mCursor;
public DbHelper helper;
public String insertkataindonesia, insertkatatora;
public int id,temp_id;
public SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
helper = new DbHelper(this);
db = helper.getWritableDatabase();
mCursor = helper.getAll();
search = (Button) findViewById(R.id.btnSearch);
add = (Button) findViewById(R.id.btnAdd);
back = (Button) findViewById(R.id.btnBack);
indo = (EditText) findViewById(R.id.insertBahasaIndonesia);
tora = (EditText) findViewById(R.id.insertBahasaTora);
add.setEnabled(false);
search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
String result = "";
insertkataindonesia = indo.getText().toString().toLowerCase();
mCursor = db.rawQuery("SELECT _id,kata_indo, kata_tora FROM translate " + "WHERE kata_indo = '"+insertkataindonesia+"' ORDER BY kata_indo",null);
if(mCursor.moveToFirst()){
result = mCursor.getString(2);
for
(;!mCursor.isAfterLast();mCursor.moveToNext()){
result = mCursor.getString(2);
}
}
if (result.equals("")){
result = "";
Toast.makeText(Insert.this,"Kata tidak ditemukan, silahkan tambahkan kata", Toast.LENGTH_LONG).show();
add.setEnabled(true);
}
tora.setText(result);
}});
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
insertkataindonesia = indo.getText().toString().toLowerCase();
insertkatatora = tora.getText().toString().toLowerCase();
if (insertkatatora.equals("") && insertkataindonesia.equals("")){
Toast.makeText(Insert.this,"Tidak ada kata untuk disimpan", Toast.LENGTH_LONG).show();
}
else if (insertkatatora.equals("")){
Toast.makeText(Insert.this,"Tidak ada kata toraja untuk disimpan", Toast.LENGTH_LONG).show();
}
else if (insertkataindonesia.equals("")){
Toast.makeText(Insert.this,"Tidak ada kata Indonesia untuk disimpan", Toast.LENGTH_LONG).show();
}
else if (id==-1){
Toast.makeText(Insert.this,"Kata sudah ada di database, silahkan hapus dulu", Toast.LENGTH_LONG).show();
}
else{
helper.insertKey(insertkataindonesia, insertkatatora);
Toast.makeText(Insert.this,"Kata telah disimpan", Toast.LENGTH_SHORT).show();
indo.setText("");
tora.setText("");
}
}
});
back.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
Intent menu = new Intent(Insert.this,
MainActivity.class);
menu.putExtra("pesan", "From Insert Menu");
startActivity(menu);
}
});
}
}
and this is the class for dbhelper.java
package com.han;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="translate.sql";
public static final String KEY_ROWID = "_id";
private static final int VERSION = 1;
private static File DATABASE_FILE;
private boolean mInvalidDatabaseFile = false;
private boolean mIsUpgraded = false;
private Context mContext;
private int mOpenConnections = 0;
private static DbHelper mInstance;
synchronized static public DbHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new
DbHelper(context.getApplicationContext());
}
return mInstance;
}
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
this.mContext = context;
SQLiteDatabase db = null;
try {
db = getReadableDatabase();
if (db != null) {
db.close();
}
DATABASE_FILE =
context.getDatabasePath(DATABASE_NAME);
if (mInvalidDatabaseFile) {
copyDatabase();
}
if (mIsUpgraded) {
doUpgrade();
}
}catch (SQLiteException e) {
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onCreate(SQLiteDatabase db) {
mInvalidDatabaseFile = true;
}
#Override
public void onUpgrade(SQLiteDatabase database, int old_version,
int new_version) {
mInvalidDatabaseFile = true;
mIsUpgraded = true;
}
private void doUpgrade() {
}
#Override
public synchronized void onOpen(SQLiteDatabase db) {
super.onOpen(db);
mOpenConnections++;
if (!db.isReadOnly()) {
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public synchronized void close() {
mOpenConnections--;
if (mOpenConnections == 0) {
super.close();
}
}
private void copyDatabase() {
AssetManager assetManager =
mContext.getResources().getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(DATABASE_NAME);
out = new FileOutputStream(DATABASE_FILE);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch
(IOException e) {}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {}
}
}
setDatabaseVersion();
mInvalidDatabaseFile = false;
}
private void setDatabaseVersion() {
SQLiteDatabase db = null;
try {
db = SQLiteDatabase.openDatabase(DATABASE_FILE.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
db.execSQL("PRAGMA user_version = " + VERSION);
} catch (SQLiteException e ) {
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
public Cursor getAll (){
return(getReadableDatabase().rawQuery("SELECT _id, kata_indo, kata_tora from translate ORDER BY _id ASC",null));
}
public void insertKey(String indo, String tora){
ContentValues cv = new ContentValues();
cv.put("kata_indo", indo);
cv.put("kata_tora", tora);
getWritableDatabase().insert("translate","kata_indo", cv);
}
public void delete(long id){
getWritableDatabase().delete("translate", KEY_ROWID + "=" + id, null);
}
}
and here is the logcat
11-18 00:16:38.489: E/AndroidRuntime(396): FATAL EXCEPTION: main
11-18 00:16:38.489: E/AndroidRuntime(396): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.han/com.han.Insert}: android.database.sqlite.SQLiteException: no such table: translate: , while compiling: SELECT _id, kata_indo, kata_tora from translate ORDER BY _id ASC
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.os.Handler.dispatchMessage(Handler.java:99)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.os.Looper.loop(Looper.java:123)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-18 00:16:38.489: E/AndroidRuntime(396): at java.lang.reflect.Method.invokeNative(Native Method)
11-18 00:16:38.489: E/AndroidRuntime(396): at java.lang.reflect.Method.invoke(Method.java:521)
11-18 00:16:38.489: E/AndroidRuntime(396): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-18 00:16:38.489: E/AndroidRuntime(396): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-18 00:16:38.489: E/AndroidRuntime(396): at dalvik.system.NativeStart.main(Native Method)
11-18 00:16:38.489: E/AndroidRuntime(396): Caused by: android.database.sqlite.SQLiteException: no such table: translate: , while compiling: SELECT _id, kata_indo, kata_tora from translate ORDER BY _id ASC
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1315)
11-18 00:16:38.489: E/AndroidRuntime(396): at com.han.DbHelper.getAll(DbHelper.java:149)
11-18 00:16:38.489: E/AndroidRuntime(396): at com.han.Insert.onCreate(Insert.java:31)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-18 00:16:38.489: E/AndroidRuntime(396): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
Appreciate your help.
This error: no such table: translate, when you are SURE that the table's name and the request are written properly, typically means that you are working on an empty DB or that a table is missing because the creation of this one failed for some reasons.
For example I'm sure that there is the first access you make to the database right for this table? If you select something you will see that you have no table or data.
This error come from an error while creating the db. Basically what most of the apps are doing is creating an empty db in the device and then copying the content of the one provided with the app, in your asset folder, to the empty one. However if there is an error in the process the copy is cancelled and your database remains empty. If you create all the db programmatically it should mean that the table creation failed.
Try to Select * on your db to see if there is content or not, then check your db creation process. You'll probably find out that one of your tables is missing, or that the creation of the db failed.
I'm trying to insert and retrieve data from database in eclipse using sqlite, but it shows a RuntimeError. I create a layout with three edit texts and one button to create simple information from but nothing is created. I create java database with the following code:
package com.example.databasetest;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "teacher";
private static final String TABLE_NAME = "teacher_table";
private static final String NAME = "teacher_name";
private static final String FATHER_NAME = "father_name";
private static final String MOTHER_NAME = "mother_name";
SQLiteDatabase data=this.getWritableDatabase();
Context ctx;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx=context;
Log.d("DATABASE OPERATION", "DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase db) {
data=db;
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " INTEGER,"
+ ");");
Log.d("DATABASE OPERATION", "TABLE CREATED");
}
public void open() throws SQLException
{
DBHelper db1 = new DBHelper(ctx);
data = db1.getWritableDatabase();
}
public void close()
{
data.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXCEPTION EXISTS");
onCreate(db);
}
public void onInsert(DBHelper db,String name,String f_name, String m_name)
{
SQLiteDatabase sql= db.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("teacher_name",name);
cv.put("father_name", f_name);
cv.put("mother_name", m_name);
sql.insert(TABLE_NAME, null, cv);
Log.d("DATABASE OPERATION", "ONE ROW INSERTED.....");
}
}
AND java file as...
package com.example.databasetest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText NAME,FATHER,MOTHER,ID;
String name,father,mother,id;
int i=1;
Button save;
Context ctxx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NAME=(EditText)findViewById(R.id.name);
FATHER=(EditText)findViewById(R.id.father_name);
MOTHER=(EditText)findViewById(R.id.mother_name);
ID=(EditText)findViewById(R.id.emp_id);
save=(Button)findViewById(R.id.submit);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
id=ID.getText().toString();
name=NAME.getText().toString();
father=FATHER.getText().toString();
mother=MOTHER.getText().toString();
if(id.equals(i))
{
Toast.makeText(getBaseContext(), "not allow insertion", Toast.LENGTH_LONG).show();
}
else
{
DBHelper DB=new DBHelper(ctxx);
DB.open();
DB.onInsert(DB, name, father, mother);
Toast.makeText(getBaseContext(), "insertion sucessful", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
and its show run time error when i click on button as in log cat..
05-08 02:54:05.932: D/AndroidRuntime(922): Shutting down VM
05-08 02:54:05.999: W/dalvikvm(922): threadid=1: thread exiting with uncaught exception (group=0x41465700)
05-08 02:54:06.189: E/AndroidRuntime(922): FATAL EXCEPTION: main
05-08 02:54:06.189: E/AndroidRuntime(922): java.lang.NullPointerException
05-08 02:54:06.189: E/AndroidRuntime(922): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.example.databasetest.DBHelper.<init>(DBHelper.java:22)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:49)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.view.View.performClick(View.java:4240)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.view.View$PerformClick.run(View.java:17721)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Handler.handleCallback(Handler.java:730)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Handler.dispatchMessage(Handler.java:92)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Looper.loop(Looper.java:137)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.app.ActivityThread.main(ActivityThread.java:5103)
05-08 02:54:06.189: E/AndroidRuntime(922): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 02:54:06.189: E/AndroidRuntime(922): at java.lang.reflect.Method.invoke(Method.java:525)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-08 02:54:06.189: E/AndroidRuntime(922): at dalvik.system.NativeStart.main(Native Method)
05-08 02:54:09.589: I/Process(922): Sending signal. PID: 922 SIG: 9
ctxx is never initialzed, and this probably the cause of the crash. Generally speaking, when you deal with Activity and Fragment subclass, you almost never need to keep a reference to the Context. Activity is a subclass of Context, and usually this is enough. In a Fragment you can retrieve the context of the Activity hosting the Fragment with getActivity()
Chante
DBHelper DB=new DBHelper(ctxx);
with
DBHelper DB=new DBHelper(MainActivity.this);
As #DerGolem pointed out, you are using the type INTEGER for the column MOTHER_NAME. Probably you want to use TEXT, instead, and you will also need a the primary key "_id"
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " TEXT"
+ ");");
In your activity initialize the ctxx in onCreate:
ctxx=this;
or
DBHelper DB=new DBHelper(MainActivity.this);
whenever you will initialize database object will null you will get sqlite locked exception.
Also fixe this
public void onCreate(SQLiteDatabase db) {
data=db;
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " TEXT"
+ ");");
Log.d("DATABASE OPERATION", "TABLE CREATED");
}
for "INTEGER," remove ,.
and intialise it like this DBHelper.
DBHelper DB=new DBHelper(MainActivity.this);
You need init ctxx in onCreate() method:
ctxx = this;
If you want to know more about sqlite on android -> ok. But if you want to less code you can try some SqliteLibrary for android. (example ActiveAndroid, GreenDAO.....).
When I attempt to connect to a local Database on my computer I get a list of problems.
07-31 21:29:53.036: I/System.out(1470): 1
07-31 21:29:53.046: I/System.out(1470): 2
07-31 21:29:53.106: I/System.out(1470): 3
07-31 21:29:53.326: W/EGL_emulation(1470): eglSurfaceAttrib not implemented
07-31 21:30:00.126: E/JSON(1470):{"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}n
07-31 21:30:00.126: I/System.out(1470): 4
07-31 21:30:00.156: I/System.out(1470): 5
07-31 21:30:00.156: I/System.out(1470): ERROR
07-31 21:30:00.186: W/System.err(1470): java.lang.NullPointerException
07-31 21:30:00.186: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:138)
07-31 21:30:00.196: W/System.err(1470): at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:1)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 21:30:00.196: W/System.err(1470): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 21:30:00.196: W/System.err(1470): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 21:30:00.206: W/System.err(1470): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 21:30:00.206: W/System.err(1470): at java.lang.Thread.run(Thread.java:841)
07-31 21:30:00.206: I/System.out(1470): 9
07-31 21:30:00.326: D/AndroidRuntime(1470): Shutting down VM
07-31 21:30:00.326: W/dalvikvm(1470): threadid=1: thread exiting with uncaught exception (group=0xb1a32ba8)
07-31 21:30:00.336: E/AndroidRuntime(1470): FATAL EXCEPTION: main
07-31 21:30:00.336: E/AndroidRuntime(1470): Process: com.example.skelotong, PID: 1470
07-31 21:30:00.336: E/AndroidRuntime(1470): java.lang.NullPointerException
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:184)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.example.skelotong.RegularUsercreation$ruc.onPostExecute(RegularUsercreation.java:1)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Handler.dispatchMessage(Handler.java:102)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.os.Looper.loop(Looper.java:136)
07-31 21:30:00.336: E/AndroidRuntime(1470): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 21:30:00.336: E/AndroidRuntime(1470): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-31 21:30:00.336: E/AndroidRuntime(1470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-31 21:30:00.336: E/AndroidRuntime(1470): at dalvik.system.NativeStart.main(Native Method)
07-31 21:30:03.356: I/Process(1470): Sending signal. PID: 1470 SIG: 9
07-31 21:30:05.946: D/dalvikvm(1499): GC_FOR_ALLOC freed 179K, 12% free 3467K/3932K, paused 141ms, total 144ms
07-31 21:30:06.636: D/(1499): HostConnection::get() New Host Connection established 0xb8f39498, tid 1499
07-31 21:30:06.786: W/EGL_emulation(1499): eglSurfaceAttrib not implemented
07-31 21:30:06.796: D/OpenGLRenderer(1499): Enabling debug mode 0
Here is the code that I attempt to run.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegularUsercreation extends ActionBarActivity implements Runnable {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
EditText inputUsername;
EditText dateofbirth;
EditText zip;
// EditText skils;
// JSON Response node names
private static String KEY_SUCCESS = "success";
// private static String KEY_ERROR = "error";
// private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private Handler mHandler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regular_usercreation);
}
public void clicker(View view) {
new ruc().execute((String[]) null);
}
public void ss(View view) {
Intent i = new Intent(getApplicationContext(), RegisterClass.class);
startActivity(i);
// Close Registration View
finish();
}
private class ruc extends AsyncTask<String, Integer, Boolean> {
final ProgressDialog pd = new ProgressDialog(RegularUsercreation.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setMessage("Please wait");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
System.out.println("1");
}
#Override
protected Boolean doInBackground(String... params) {
System.out.println(2);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.FullName2);
inputEmail = (EditText) findViewById(R.id.Email2);
inputPassword = (EditText) findViewById(R.id.Password2);
inputUsername = (EditText) findViewById(R.id.Username2);
dateofbirth = (EditText) findViewById(R.id.DOB2);
zip = (EditText) findViewById(R.id.ZipCode2);
btnRegister = (Button) findViewById(R.id.create2);
btnLinkToLogin = (Button) findViewById(R.id.cancel2);
registerErrorMsg = (TextView) findViewById(R.id.errormessage3);
// skils = (EditText) findViewById(R.id.skills1);
System.out.println("3");
// Register Button Click event
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String usernmae = inputUsername.getText().toString();
String birth = dateofbirth.getText().toString();
String zipcode = zip.getText().toString();
// String skills = skils.getText().toString();
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.registerUser(name, email, password,
usernmae, birth, zipcode);
System.out.println(4);
// check for login response
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
System.out.println("5");
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
System.out.println(6);
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
System.out.println("7");
return true;
} else {
System.out.println("ERROR");
// Error in registration
//registerErrorMsg
// .setText("Error occured in registration");
return false;
}
}
} catch (JSONException e) {
publishProgress(1);
e.printStackTrace();
System.out.println("9");
return false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if (values.equals(1)) {
pd.setMessage("Almost Done");
}
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == true) {
// launch dashboard
Intent dashboard = new Intent(getApplicationContext(),
HomePage.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}
if (result == false) {
registerErrorMsg.setText("Error occured in registration");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.regular_usercreation, 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);
}
#Override
public void run() {
// TODO Auto-generated method stub
mHandler.post(new Runnable() {
public void run() {
new ruc();
ruc.execute(RegularUsercreation.this);
}
});
}
}
How can this problem be fixed and what can be done in the future to prevent this?
Also why does this happen.
from the looks of is either res is null or something's null within these lines
if (Integer.parseInt(res) == 1) {
publishProgress(1);
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
However its hard to be sure. publishProgress or getApplicationContext may have something throwing the NullPointerException as well. Try this for debugging the problem : since you're using eclipse, you can use debugger instead of println, its way more powerful. A useful tutorial. If you don't want to use the debugger, print the values instead of numbers. They'll provide much more useeful context.
I'm made a counter app and I want to add a save function where it saves the current number of the counter into the database. But when I try to run it, its closes unexpectedly.
The logcat and code is below
package com.example.testdatabase;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add;
Button sub;
Button save;
TextView display;
private SharedPreferences prefs;
private String prefName = "MyPref";
MySQLiteHelper db = new MySQLiteHelper(this);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.add(counter);
}
});
}
protected void onPause()
{
super.onPause();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("counter", counter);
edit.commit();
}
protected void onResume()
{
super.onResume();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
counter = prefs.getInt("counter", counter);
display.setText("Counter: " + counter);
}
}
the class the handles the database stuff
package com.example.testdatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CountDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create counter table
String CREATE_COUNT_TABLE = "CREATE TABLE count ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"amount INT )";
// create books table
db.execSQL(CREATE_COUNT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older counter table if existed
db.execSQL("DROP TABLE IF EXISTS count");
// create fresh count table
this.onCreate(db);
}
// Books table name
private static final String TABLE_COUNTER= "count";
// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_AMOUNT = "amount";
private static final String[] COLUMNS = {KEY_ID,KEY_AMOUNT};
public void add(int counter){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_AMOUNT, counter); // get counter amount
// 3. insert
db.insert(TABLE_COUNTER, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
the logcat
15:08:30.713: D/AndroidRuntime(302): Shutting down VM
11-17 15:08:30.713: W/dalvikvm(302): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-17 15:08:30.742: E/AndroidRuntime(302): FATAL EXCEPTION: main
11-17 15:08:30.742: E/AndroidRuntime(302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdatabase/com.example.testdatabase.MainActivity}: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.os.Looper.loop(Looper.java:123)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-17 15:08:30.742: E/AndroidRuntime(302): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302): at java.lang.reflect.Method.invoke(Method.java:521)
11-17 15:08:30.742: E/AndroidRuntime(302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-17 15:08:30.742: E/AndroidRuntime(302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-17 15:08:30.742: E/AndroidRuntime(302): at dalvik.system.NativeStart.main(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302): Caused by: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302): at com.example.testdatabase.MainActivity.onCreate(MainActivity.java:49)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-17 15:08:30.742: E/AndroidRuntime(302): ... 11 more
any ideas?
Program throws an exception in :
save.setOnClickListener(new View.OnClickListener() ...
It seems that Button save is not initialized.
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.