Accessing SQLite database from fragment - java

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);
}

Related

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

Error: sqlite returned: error code = 1, msg = no such table

I am working on a small app which stores the place latitude and longitude in SQLite database. I have three classes as follows:
AddPlaceActyivity.java
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.rememberthislocation.R;
public class AddPlaceActivity extends Activity{
Button btn_remember,btn_maps;
Fragment fr;
Button addlocation;
EditText locationname;
String mylocationname,mylatitude,mylongitude;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("my","In oncreateview");
setContentView(R.layout.remember_fragment);
addlocation = (Button)findViewById(R.id.btn_addlocation);
locationname = (EditText)findViewById(R.id.locationname);
mylocationname = locationname.getText().toString();
Log.d("my","value 1 taken");
mylatitude = "0.0";
mylongitude = "0.0";
Log.d("my", "data values taken");
addlocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MySqliteHelper db = new MySqliteHelper(getApplicationContext());
db.addPlaces(new Place(mylocationname,mylatitude,mylongitude));
}
});
}
}
MySqliteHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySqliteHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String KEY_ID = "id";
private static final String KEY_PLACENAME = "placename";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String TABLE_NAME = "places";
public MySqliteHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//actual query = create table places (id primary key autoincrement, placename taxt, latitude real, longitude real);
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
try {
db.execSQL(query);
Log.d("my", "Successfully created table: " + query);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS places");
this.onCreate(db);
}
public void addPlaces(Place place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues convalues = new ContentValues();
convalues.put(KEY_PLACENAME,place.getname());
convalues.put(KEY_LATITUDE,place.getlatitude());
convalues.put(KEY_LONGITUDE,place.getlongitude());
db.insert(TABLE_NAME, null, convalues);
Log.d("my","db.insert(TABLE_NAME, null, convalues)");
Log.d("my", "Values inserted");
db.close();
}
}
Place.java
public class Place {
String mname,mlatitude,mlongitude,mstring;
public Place(String name, String latitude, String longitude)
{
mname = name;
mlatitude = latitude;
mlongitude = longitude;
}
public Place() {
// TODO Auto-generated constructor stub
}
public void setname(String placename)
{
mname = placename;
}
public String getname()
{
return mname;
}
public void setlatitude(String latitude)
{
mlatitude=latitude;
}
public String getlatitude()
{
return mlatitude;
}
public void setlongitude(String longitude)
{
mlongitude = longitude;
}
public String getlongitude()
{
return mlongitude;
}
}
And my logcat log:
11-20 17:40:02.770: D/my(10604): In oncreateview
11-20 17:40:02.890: D/my(10604): acivity layout initialized
11-20 17:40:02.950: I/PGA(10604): New SOCKET connection: berthislocation (pid 10604, tid 10604)
11-20 17:40:16.510: D/my(11196): in remember's onclick
11-20 17:40:16.540: D/my(11196): intent started
11-20 17:40:16.560: D/my(11196): In oncreateview
11-20 17:40:16.560: D/my(11196): value 1 taken
11-20 17:40:16.560: D/my(11196): data values taken
11-20 17:40:27.290: I/SqliteDatabaseCpp(11196): sqlite returned: error code = 1, msg = no such table: places, db=/data/data/com.example.rememberthislocation/databases/contactsManager
11-20 17:40:27.290: E/SQLiteDatabase(11196): Error inserting longitude=0.0 latitude=0.0 placename=
11-20 17:40:27.290: E/SQLiteDatabase(11196): android.database.sqlite.SQLiteException: no such table: places: , while compiling: INSERT INTO places(longitude,latitude,placename) VALUES (?,?,?)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:260)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1718)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1591)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.MySqliteHelper.addPlaces(MySqliteHelper.java:74)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.AddPlaceActivity$1.onClick(AddPlaceActivity.java:52)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View.performClick(View.java:3511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View$PerformClick.run(View.java:14105)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.handleCallback(Handler.java:605)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Looper.loop(Looper.java:137)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invokeNative(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invoke(Method.java:511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at dalvik.system.NativeStart.main(Native Method)
Clearly the error is in MySqliteHelper.java
Error: sqlite returned: error code = 1, msg = no such table: places
So, my MySqliteHelper class's oncreate() isn't called. I tried for hours..but can't find the solution. Can anyone help me?
You have bugs in your onCreate() that are hidden by the catch:
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
Missing whitespace, change to:
String query = "CREATE TABLE " +TABLE_NAME + "( " + KEY_ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
" TEXT, "+KEY_LATITUDE+
" REAL, "+KEY_LONGITUDE+ " REAL)";
Remove the try-catch. If there's a problem, the framework should be thrown an exception. If onCreate() returns normally, the framework thinks the database was set up successfully. onCreate() is only called once when the database is first set up.
Uninstall your app or clear its data to get rid of the old empty database file and to get onCreate() rerun.
Further reading: When is SQLiteOpenHelper onCreate() / onUpgrade() run?

Error while create Progress Dialog on Database create

I would like to implement a progress dialog when the database load the data for the first time.
this is my code
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(ENG_FRA_TABLE_CREATE);
loadDictionaryEngFra();
new InitDB().execute();
}
public class InitDB extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(mHelperContext, "", "Wait", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
If i try to run the app with this progress dialog, it throw this error list
04-18 23:16:30.886: E/SQLiteLog(26059): (1) no such table: ENG_FRAdictionary
04-18 23:16:30.896: E/SQLiteDatabase(26059): Error inserting suggest_text_1=abbey suggest_text_2=n. a monastery ruled by an abbot
04-18 23:16:30.896: E/SQLiteDatabase(26059): android.database.sqlite.SQLiteException: no such table: ENG_FRAdictionary (code 1): , while compiling: INSERT INTO ENG_FRAdictionary(suggest_text_1,suggest_text_2) VALUES (?,?)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:686)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1573)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1445)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.addWordEngFra(DictionaryDatabaseEngFra.java:238)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.loadWordsEngFra(DictionaryDatabaseEngFra.java:218)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.access$1(DictionaryDatabaseEngFra.java:208)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$1.run(DictionaryDatabaseEngFra.java:200)
04-18 23:16:30.896: E/SQLiteDatabase(26059): at java.lang.Thread.run(Thread.java:856)
04-18 23:16:30.896: E/DictionaryDatabaseEngFra(26059): unable to add word: abbey
04-18 23:16:30.896: W/dalvikvm(26059): threadid=14: thread exiting with uncaught exception (group=0x41d24930)
04-18 23:16:30.896: E/AndroidRuntime(26059): FATAL EXCEPTION: Thread-51326
04-18 23:16:30.896: E/AndroidRuntime(26059): java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.example.searchtoto/databases/dictionaryEngFra
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1543)
04-18 23:16:30.896: E/AndroidRuntime(26059): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1445)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.addWordEngFra(DictionaryDatabaseEngFra.java:238)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.loadWordsEngFra(DictionaryDatabaseEngFra.java:218)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.access$1(DictionaryDatabaseEngFra.java:208)
04-18 23:16:30.896: E/AndroidRuntime(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$1.run(DictionaryDatabaseEngFra.java:200)
04-18 23:16:30.896: E/AndroidRuntime(26059): at java.lang.Thread.run(Thread.java:856)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): Search suggestions query threw an exception.
04-18 23:16:30.996: W/SuggestionsAdapter(26059): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.ViewRootImpl.setView(ViewRootImpl.java:804)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.Dialog.show(Dialog.java:282)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.ProgressDialog.show(ProgressDialog.java:116)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.ProgressDialog.show(ProgressDialog.java:99)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper$InitDB.onPreExecute(DictionaryDatabaseEngFra.java:174)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.AsyncTask.execute(AsyncTask.java:534)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra$DictionaryOpenHelper.onCreate(DictionaryDatabaseEngFra.java:162)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra.query(DictionaryDatabaseEngFra.java:113)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryDatabaseEngFra.getWordMatchesEngFra(DictionaryDatabaseEngFra.java:96)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryProviderEngFra.getSuggestions(DictionaryProviderEngFra.java:107)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at com.example.searchtoto.dictionary.en.DictionaryProviderEngFra.query(DictionaryProviderEngFra.java:81)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentProvider.query(ContentProvider.java:652)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentProvider$Transport.query(ContentProvider.java:189)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentResolver.query(ContentResolver.java:375)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.content.ContentResolver.query(ContentResolver.java:318)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.app.SearchManager.getSuggestions(SearchManager.java:930)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.SuggestionsAdapter.runQueryOnBackgroundThread(SuggestionsAdapter.java:200)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.CursorFilter.performFiltering(CursorFilter.java:49)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.Handler.dispatchMessage(Handler.java:99)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.Looper.loop(Looper.java:137)
04-18 23:16:30.996: W/SuggestionsAdapter(26059): at android.os.HandlerThread.run(HandlerThread.java:60)
whitout the implementation of the progress dialog, the app run fine
this is the activity
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
/**
* Contains logic to return specific words from the dictionary, and
* load the dictionary table when it needs to be created.
*/
public class DictionaryDatabaseEngFra extends SearchableDictionaryEngFra{
private static final String TAG = "DictionaryDatabaseEngFra";
//The columns we'll include in the dictionary table
public static final String KEY_WORD_ENG_FRA = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION_ENG_FRA = SearchManager.SUGGEST_COLUMN_TEXT_2;
private static final String DATABASE_NAME = "dictionaryEngFra";
private static final String ENG_FRA_TABLE = "ENG_FRAdictionary";
private static final int DATABASE_VERSION = 2;
private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,String> mColumnMapEngFra = buildColumnMapEngFra();
static File ENG_FRA = new File(Environment.getExternalStorageDirectory().getPath() + "/dic/dictionary/engfra./", "eng_fra.txt");
/**
* Constructor
* #param context The Context within which to work, used to create the DB
*/
public DictionaryDatabaseEngFra(Context context) {
mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}
/**
* Builds a map for all columns that may be requested, which will be given to the
* SQLiteQueryBuilder. This is a good way to define aliases for column names, but must include
* all columns, even if the value is the key. This allows the ContentProvider to request
* columns w/o the need to know real column names and create the alias itself.
*/
private static HashMap<String,String> buildColumnMapEngFra() {
HashMap<String,String> mapEngFra = new HashMap<String,String>();
mapEngFra.put(KEY_WORD_ENG_FRA, KEY_WORD_ENG_FRA);
mapEngFra.put(KEY_DEFINITION_ENG_FRA, KEY_DEFINITION_ENG_FRA);
mapEngFra.put(BaseColumns._ID, "rowid AS " +
BaseColumns._ID);
mapEngFra.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
mapEngFra.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
return mapEngFra;
}
public Cursor getWordEngFra(String rowId, String[] columns) {
String selection = "rowid = ?";
String[] selectionArgs = new String[] {rowId};
return query(selection, selectionArgs, columns);
}
public Cursor getWordMatchesEngFra(String query, String[] columns) {
String selection = KEY_WORD_ENG_FRA + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
/* The SQLiteBuilder provides a map for all possible columns requested to
* actual columns in the database, creating a simple column alias mechanism
* by which the ContentProvider does not need to know the real column names
*/
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(ENG_FRA_TABLE);
builder.setProjectionMap(mColumnMapEngFra);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
/**
* This creates/opens the database.
*/
private static class DictionaryOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
/* Note that FTS3 does not support column constraints and thus, you cannot
* declare a primary key. However, "rowid" is automatically used as a unique
* identifier, so when making requests, we will use "_id" as an alias for "rowid"
*/
private static final String ENG_FRA_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + ENG_FRA_TABLE +
" USING fts3 (" +
KEY_WORD_ENG_FRA + ", " +
KEY_DEFINITION_ENG_FRA + ");";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(ENG_FRA_TABLE_CREATE);
loadDictionaryEngFra();
new InitDB().execute();
}
public class InitDB extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(mHelperContext, "", "Wait", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
/**
* Starts a thread to load the database table with words
*/
private void loadDictionaryEngFra() {
new Thread(new Runnable() {
public void run() {
try {
loadWordsEngFra();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadWordsEngFra() throws IOException {
Log.d(TAG, "Loading words eng_fra...");
FileInputStream fileInputStream = new FileInputStream(ENG_FRA);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2) continue;
long id = addWordEngFra(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
/**
* Add a word to the dictionary.
* #return rowId or -1 if failed
*/
public long addWordEngFra(String word, String definition) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_WORD_ENG_FRA, word);
initialValues.put(KEY_DEFINITION_ENG_FRA, definition);
return mDatabase.insert(ENG_FRA_TABLE, null, initialValues);
}
/**
* Add a word to the dictionary.
* #return rowId or -1 if failed
*/
#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 " + ENG_FRA_TABLE);
onCreate(db);
}
}
}
This looks like an SQL error.
04-18 23:16:30.896: E/SQLiteDatabase(26059): Error inserting suggest_text_1=abbey suggest_text_2=n. a monastery ruled by an abbot
04-18 23:16:30.896: E/SQLiteDatabase(26059): android.database.sqlite.SQLiteException: no such table: ENG_FRAdictionary (code 1): , while compiling: INSERT INTO ENG_FRAdictionary(suggest_text_1,suggest_text_2) VALUES (?,?)
It doesn't look like your ENG_FRAdictionary table exists.
The problem is in your sqlite db. I can't see a problem with progress dialog
Check your db creation statement and table names. Also check the sqlitehelper class
And let us know what happens

android: trying to add counter information to sqlite database

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.

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.

Categories