android: trying to add counter information to sqlite database - java

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.

Related

eclipse calling database error

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.

Android application force closes on insertion in database

The app I'm trying to make force closes on insertion into database. I think there's something wrong in the DBAdapter class.In the transaction class I'm calling the inserttransaction method using an object of the DBAdapter class.
DBAdapter class
package com.example.kharchapaani;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter extends SQLiteOpenHelper {
private static final String DATABASE_NAME="KPdetail";
private static final int DATABASE_VERSION=1;
private static final String TABLE1_NAME="BALANCE";
private static final String TABLE2_NAME="TRANSACTION";
private static final String TABLE3_NAME="LENT";
private Context context;
private static final String KEY_NAME="NAME";
private static final String SOURCE="SOURCE";
private static final String AMOUNT="AMOUNT";
private static final String CATEGORY="CATEGORY";
private static final String DATE="DATE";
private static final String PAID="PAID";
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
String CREATE_BALANCE_TABLE="CREATE TABLE "+TABLE1_NAME +"("+SOURCE+" TEXT"+","+AMOUNT+" REAL"+")";
arg0.execSQL(CREATE_BALANCE_TABLE);
String CREATE_TRANSACTION_TABLE="CREATE TABLE "+TABLE2_NAME+"("+AMOUNT+" REAL"+","+DATE+" DATETIME"+","+CATEGORY+" TEXT"+","+SOURCE+" TEXT"+")";
arg0.execSQL(CREATE_TRANSACTION_TABLE);
String CREATE_LENT_TABLE="CREATE TABLE "+TABLE3_NAME+"("+KEY_NAME+" TEXT"+","+AMOUNT+" REAL"+","+DATE+" DATETIME"+","+SOURCE+" TEXT"+","+PAID +" INTEGER"+")";
arg0.execSQL(CREATE_LENT_TABLE);
}
public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
// TODO Auto-generated constructor stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int oldversion, int newversion) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXISTS BALANCE");
arg0.execSQL("DROP TABLE IF EXISTS TRANSACTION");
arg0.execSQL("DROP TABLE IF EXISTS LENT");
onCreate(arg0);
}
void insertbalance(String source,float amount)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(SOURCE,source);
values.put(AMOUNT,amount);
db.insert(TABLE1_NAME, null, values);
db.close();
}
void inserttransaction(float amount,String date,String category,String source)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(AMOUNT,amount);
values.put(DATE,date);
values.put(CATEGORY,category);
values.put(SOURCE,source);
db.insert(TABLE2_NAME, null, values);
db.close();
}
void insertlent(String name,float amount,String date,String source,int paid)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME,name);
values.put(AMOUNT,amount);
values.put(DATE,date);
values.put(SOURCE,source);
values.put(PAID,paid);
db.insert(TABLE3_NAME, null, values);
db.close();
}
public void clearData(){
context.deleteDatabase(DATABASE_NAME);
}
public Cursor getInsertedDatabalance() {
// TODO Auto-generated method stub
SQLiteDatabase db=this.getReadableDatabase();
return db.query(TABLE1_NAME,new String[] {SOURCE,AMOUNT}, null, null, null, null, null);
}
public Cursor getInsertedDatatransaction() {
// TODO Auto-generated method stub
SQLiteDatabase db=this.getReadableDatabase();
return db.query(TABLE2_NAME,new String[] {AMOUNT,DATE,CATEGORY,SOURCE}, null, null, null, null, null);
}
public Cursor getInsertedDatalentall() {
// TODO Auto-generated method stub
SQLiteDatabase db=this.getReadableDatabase();
return db.query(TABLE3_NAME,new String[] {KEY_NAME,AMOUNT,DATE,SOURCE}, null, null, null, null, null);
}
public Cursor getInsertedDatalentpaid() {
// TODO Auto-generated method stub
SQLiteDatabase db=this.getReadableDatabase();
return db.query(TABLE3_NAME,new String[] {KEY_NAME,AMOUNT,DATE,SOURCE},"PAID=1", null, null, null, null);
}
public Cursor getInsertedDatalentnotpaid() {
// TODO Auto-generated method stub
SQLiteDatabase db=this.getReadableDatabase();
return db.query(TABLE3_NAME,new String[] {KEY_NAME,AMOUNT,DATE,SOURCE},"PAID=0", null, null, null, null);
}
}
The class in which the inserttransaction method is called is the Transaction class:
package com.example.kharchapaani;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Transaction extends Activity {
EditText et1,et2,et3;
Button b1;
CheckBox ck1,ck2;
float amount;
String category,date,source;
Calendar cal;
DBAdapter db;
RadioGroup rg1;
RadioButton rb1;
SimpleDateFormat sdf;
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
Spinner s1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction);
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button1);
rg1=(RadioGroup)findViewById(R.id.radioGroup1);
db=new DBAdapter(this);
ck1=(CheckBox)findViewById(R.id.checkBox1);
ck2=(CheckBox)findViewById(R.id.checkBox2);
sdf=new SimpleDateFormat("dd/MM/yyyy");
s1=(Spinner)findViewById(R.id.spinner1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
list.add("Laundry");
list.add("Grocery");
list.add("Entertainment");
list.add("Eating Out");
list.add("Gifts");
adapter.notifyDataSetChanged();
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{amount=Float.parseFloat(et1.getText().toString());
}
catch(Exception e)
{e.printStackTrace();}
if(ck1.isChecked()==true)
{cal = Calendar.getInstance();
date=sdf.format(cal.getTime());
}
else
{date=et2.getText().toString();}
if(ck2.isChecked()==true)
{
category=et3.getText().toString();
adapter.add(category);
adapter.notifyDataSetChanged();
}
else
{
category=String.valueOf(s1.getSelectedItem());
}
int selid=rg1.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selid);
source=rb1.getText().toString();
db.inserttransaction(amount, date, category, source);
Toast.makeText(getBaseContext(), "Amount: "+amount+"\nDate: "+date+"\nCategory: "+category+"\nSource: "+source,Toast.LENGTH_LONG).show();
}
});
}
#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, menu);
return true;
}
}
Logcat:
07-04 14:37:29.855: W/KeyCharacterMap(277): No keyboard for id 0
07-04 14:37:29.855: W/KeyCharacterMap(277): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
07-04 14:37:35.294: I/Database(277): sqlite returned: error code = 1, msg = near "TRANSACTION": syntax error
07-04 14:37:35.304: E/Database(277): Error inserting DATE=04/07/2015 SOURCE=Wallet CATEGORY=Laundry AMOUNT=123.0
07-04 14:37:35.304: E/Database(277): android.database.sqlite.SQLiteException: near "TRANSACTION": syntax error: , while compiling: INSERT INTO TRANSACTION(DATE, SOURCE, CATEGORY, AMOUNT) VALUES(?, ?, ?, ?);
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:36)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1145)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1536)
07-04 14:37:35.304: E/Database(277): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
07-04 14:37:35.304: E/Database(277): at com.example.kharchapaani.DBAdapter.inserttransaction(DBAdapter.java:64)
07-04 14:37:35.304: E/Database(277): at com.example.kharchapaani.Transaction$1.onClick(Transaction.java:89)
07-04 14:37:35.304: E/Database(277): at android.view.View.performClick(View.java:2408)
07-04 14:37:35.304: E/Database(277): at android.view.View$PerformClick.run(View.java:8816)
07-04 14:37:35.304: E/Database(277): at android.os.Handler.handleCallback(Handler.java:587)
07-04 14:37:35.304: E/Database(277): at android.os.Handler.dispatchMessage(Handler.java:92)
07-04 14:37:35.304: E/Database(277): at android.os.Looper.loop(Looper.java:123)
07-04 14:37:35.304: E/Database(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-04 14:37:35.304: E/Database(277): at java.lang.reflect.Method.invokeNative(Native Method)
07-04 14:37:35.304: E/Database(277): at java.lang.reflect.Method.invoke(Method.java:521)
07-04 14:37:35.304: E/Database(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-04 14:37:35.304: E/Database(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-04 14:37:35.304: E/Database(277): at dalvik.system.NativeStart.main(Native Method)
Removed DATE from the Tables and the methods..and still there's some error..so i guess it doesn't have much to do with the datatype of DATE
07-04 16:20:46.815: E/Database(674): Error inserting SOURCE=Wallet AMOUNT=12.0 CATEG=Laundry
check SQLite Keywords
your table name is conflict with TRANSACTION table of mysql. change your table name.
In your 'inserttransaction' method you take date as a String.
void inserttransaction(float amount,String date,String category,String source)
But in your 'onCreate' method you define the column as DATETIME.
String CREATE_TRANSACTION_TABLE="CREATE TABLE "+TABLE2_NAME+"("+AMOUNT+" REAL"+","+DATE+" DATETIME"+","+CATEGORY+" TEXT"+","+SOURCE+" TEXT"+")";
DATETIME resolves to type NUMERIC, not TEXT.
Check section 2.2 in this link
You could do one the following:
Option A
Change the table definition to type TEXT.
Option B
Convert the date to a number in your 'inserttransaction' method.
Problem is Error inserting DATE=04/07/2015
Put double quotes across your entry ie "04/07/2015" so while inserting append your string as "\""+DATE+"\""
And voila your problem is gone you can use DATETIME format

Accessing SQLite database from fragment

My app contains MainActivity class and several fragments.
One of the is the registration fragment which I want it to be able tho interact with my database which should contain only one table named USERS to whom I will CRUD.
I've opened the MySQLiteOpenHelper class that extends SQLiteOpenHelper and created a User class as well.
I've declared:
MySQLiteOpenHelper db = new MySQLiteOpenHelper(this);
in the activity's onCreate method.
My question is how do I interact with this db from the fragments?
I've tried the following code but it didn't work:
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class registration extends Fragment {
public registration() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.registration, container,
false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
final EditText etFirstName = (EditText) getActivity().findViewById(
R.id.etFirstName);
final EditText etLastName = (EditText) getActivity().findViewById(
R.id.etLastName);
final EditText etEmail = (EditText) getActivity().findViewById(
R.id.etEmail);
final EditText etUsername = (EditText) getActivity().findViewById(
R.id.etUsername);
final EditText etPassword = (EditText) getActivity().findViewById(
R.id.etPassword);
Button bDone = (Button) getActivity().findViewById(R.id.bDone);
bDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
db.addUser(new User(etFirstName.getText().toString(),
etLastName.getText().toString(), etEmail.getText()
.toString(), etUsername.getText().toString(),
etPassword.getText().toString()));
}
});
}
}
What happens now is that the moment I click the DONE button the app crushes...
Thank's!!
MySQLiteOpenHelper looks like this:
import java.util.LinkedList;
import java.util.List;
import android.R.string;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="MyDB";
private static final String TABLE_USERS="USERS";
private static final String FIRST_NAME="First_name";
private static final String LAST_NAME="Last_name";
private static final String EMAIL="Email";
private static final String USERNAME="Username";
private static final String PASSWORD="Password";
private static final String COLUMNS[]={FIRST_NAME, LAST_NAME, EMAIL, USERNAME, PASSWORD};
public MySQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_MyDB_TABLE = "CREATE TABLE USERS ( " +
"First_name TEXT, " +
"Last_name TEXT, "+
"Email KEY TEXT NOT NULL, "+
"Username TEXT NOT NULL, "+
"Password TEXT NOT NULL)";
db.execSQL(CREATE_MyDB_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS USERS");
this.onCreate(db);
}
public void addUser(User user){
Log.d("addUser", user.toString());
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(FIRST_NAME, user.getFirstName());
values.put(LAST_NAME, user.getLastName());
values.put(EMAIL, user.getEmail());
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
db.insert(TABLE_USERS, null, values);
db.close();
}
public User getUser(String Email){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=
db.query(TABLE_USERS, COLUMNS, "Email =?", new String[] {String.valueOf(Email)}, null, null, null);
if (cursor != null)
cursor.moveToFirst();
User user=new User();
user.setFirstName(cursor.getString(0));
user.setLastName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setUsername(cursor.getString(3));
user.setPassword(cursor.getString(4));
Log.d("getUser ("+Email+")", user.toString());
return user;
}
public List<User> getAllUsers(){
List<User> users=new LinkedList<User>();
String query="SELECT * FROM "+TABLE_USERS;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query, null);
User user=null;
if (cursor.moveToFirst()){
do{
user=new User();
user.setFirstName(cursor.getString(0));
user.setLastName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setUsername(cursor.getString(3));
user.setPassword(cursor.getString(4));
users.add(user);
} while (cursor.moveToNext());
}
Log.d("getAllUsers", users.toString());
return users;
}
public int updateUser(User user){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(FIRST_NAME, user.getFirstName());
values.put(LAST_NAME, user.getLastName());
values.put(EMAIL, user.getEmail());
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
int i=db.update(TABLE_USERS, values, "Email =?", new String[]{String.valueOf(user.getEmail())});
db.close();
return i;
}
public void deleteUser(User user){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_USERS, "Email =?", new String[]{String.valueOf(user.getEmail())});
db.close();
Log.d("deleteUser", user.toString());
}
}
LogCat:
04-18 12:16:09.132: E/Trace(1051): error opening trace file: No such file or directory (2)
04-18 12:16:09.404: D/libEGL(1051): loaded /system/lib/egl/libEGL_emulation.so
04-18 12:16:09.416: D/(1051): HostConnection::get() New Host Connection established 0xb9324060, tid 1051
04-18 12:16:09.492: D/libEGL(1051): loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-18 12:16:09.492: D/libEGL(1051): loaded /system/lib/egl/libGLESv2_emulation.so
04-18 12:16:09.672: W/EGL_emulation(1051): eglSurfaceAttrib not implemented
04-18 12:16:09.708: D/OpenGLRenderer(1051): Enabling debug mode 0
04-18 12:16:09.800: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb931a8e0): name, size, mSize = 1, 1048576, 1048576
04-18 12:16:09.960: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9331d10): name, size, mSize = 2, 5184, 1053760
04-18 12:16:10.068: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9309b60): name, size, mSize = 4, 20736, 1074496
04-18 12:16:10.072: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb932d4b8): name, size, mSize = 5, 9216, 1083712
04-18 12:16:10.140: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9312810): name, size, mSize = 7, 7488, 1091200
04-18 12:16:10.152: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9325d70): name, size, mSize = 8, 100, 1091300
04-18 12:16:10.212: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb93176a0): name, size, mSize = 10, 7488, 1098788
04-18 12:16:10.252: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9373798): name, size, mSize = 11, 7488, 1106276
04-18 12:16:10.336: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9315840): name, size, mSize = 12, 2304, 1108580
04-18 12:16:42.528: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9378b38): name, size, mSize = 78, 7488, 1116068
04-18 12:16:42.800: D/dalvikvm(1051): GC_CONCURRENT freed 142K, 3% free 8216K/8391K, paused 14ms+0ms, total 25ms
04-18 12:16:44.200: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9308998): name, size, mSize = 85, 7488, 1123556
04-18 12:16:44.216: D/OpenGLRenderer(1051): TextureCache::get: create texture(0xb9316848): name, size, mSize = 86, 7488, 1131044
04-18 12:16:53.192: D/addUser(1051): First name: dsfLast name: dsfdsfEmail: dsfdsfUsername: Password:
04-18 12:16:53.196: D/AndroidRuntime(1051): Shutting down VM
04-18 12:16:53.196: W/dalvikvm(1051): threadid=1: thread exiting with uncaught exception (group=0xa627b288)
04-18 12:16:53.200: E/AndroidRuntime(1051): FATAL EXCEPTION: main
04-18 12:16:53.200: E/AndroidRuntime(1051): java.lang.NullPointerException
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.craftyonhand.www.MySQLiteOpenHelper.addUser(MySQLiteOpenHelper.java:60)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.craftyonhand.www.registration$1.onClick(registration.java:47)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.view.View.performClick(View.java:4084)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.view.View$PerformClick.run(View.java:16966)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Handler.handleCallback(Handler.java:615)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Handler.dispatchMessage(Handler.java:92)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.os.Looper.loop(Looper.java:137)
04-18 12:16:53.200: E/AndroidRuntime(1051): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-18 12:16:53.200: E/AndroidRuntime(1051): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 12:16:53.200: E/AndroidRuntime(1051): at java.lang.reflect.Method.invoke(Method.java:511)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-18 12:16:53.200: E/AndroidRuntime(1051): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-18 12:16:53.200: E/AndroidRuntime(1051): at dalvik.system.NativeStart.main(Native Method)
04-18 12:16:55.792: I/Process(1051): Sending signal. PID: 1051 SIG: 9
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
Yes you need it and you also need to pass a non-null valid Context as an argument. In a fragment, you can use getActivity() to get the activity to use as a Contextonce the fragment is attached to its host activity.
Okay so it does show on logcat but for some reason it says that there is no such table USERS... As far as I know it should open it if it does not exsits. Am I wrong?
Possibly you have an older version of the database file around. Clear app data or uninstall it to remove it and make the database helper onCreate() create set up the tables for you. See When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more.
You should change this
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);//do I need this??
With
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());//do I need this??
Replace
MySQLiteOpenHelper db = new MySQLiteOpenHelper(null);
with
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());
Update onUpgrade() method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String CREATE_MyDB_TABLE = "CREATE TABLE IF NOT EXISTS USERS ( " +
"First_name TEXT, " +
"Last_name TEXT, "+
"Email KEY TEXT NOT NULL, "+
"Username TEXT NOT NULL, "+
"Password TEXT NOT NULL)";
db.execSQL(CREATE_MyDB_TABLE);
this.onCreate(db);
}

Android Java IllegalStateException: Could not execute method of the activity

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.

Cannot Resolve NullPointerException On Service Class

I have been tasked to resolve an issue for a group project at my university however I cannot seem to resolve an issue with a NullPointerException in my service class. Our goal is to create a script which continually monitors the android history until it finds a match - then executes a warning class if the service class finds a match in the browser history. The issue occurs on line 71 (of service class) however I do not know how to resolve the issue.
Service Class:
public class Service_class extends Service {
String Dirty1 = "www.pornhub.com";
String Dirty2 = "www.playboy.com";
String Dirty3 = "www.playboy.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
}
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
Main.java
import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
}}
LOGCAT:
04-15 13:58:49.980: D/AndroidRuntime(1994): Shutting down VM
04-15 13:58:50.000: W/dalvikvm(1994): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
04-15 13:58:50.000: E/AndroidRuntime(1994): FATAL EXCEPTION: main
04-15 13:58:50.000: E/AndroidRuntime(1994): java.lang.RuntimeException: Unable to create service com.nfc.linked.Service_class: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2539)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Looper.loop(Looper.java:137)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 13:58:50.000: E/AndroidRuntime(1994): at dalvik.system.NativeStart.main(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): Caused by: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.nfc.linked.Service_class.onCreate(Service_class.java:71)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2529)
04-15 13:58:50.000: E/AndroidRuntime(1994): ... 10 more
04-15 14:00:23.770: D/AndroidRuntime(2047): Shutting down VM
04-15 14:00:23.770: W/dalvikvm(2047): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
Your method managedQuery() returns null
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
So when you try to execute a method on null you will get a NullPointerException.
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null); // cursor will be null
String urls = "";
if (cursor.moveToFirst()) { // this will be NPE
Make your managedQuery() method return an instantiated Cursor object.

Categories