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
Related
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);
}
I'm made a counter app and I want to add a save function where it saves the current number of the counter into the database. But when I try to run it, its closes unexpectedly.
The logcat and code is below
package com.example.testdatabase;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add;
Button sub;
Button save;
TextView display;
private SharedPreferences prefs;
private String prefName = "MyPref";
MySQLiteHelper db = new MySQLiteHelper(this);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.add(counter);
}
});
}
protected void onPause()
{
super.onPause();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("counter", counter);
edit.commit();
}
protected void onResume()
{
super.onResume();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
counter = prefs.getInt("counter", counter);
display.setText("Counter: " + counter);
}
}
the class the handles the database stuff
package com.example.testdatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CountDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create counter table
String CREATE_COUNT_TABLE = "CREATE TABLE count ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"amount INT )";
// create books table
db.execSQL(CREATE_COUNT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older counter table if existed
db.execSQL("DROP TABLE IF EXISTS count");
// create fresh count table
this.onCreate(db);
}
// Books table name
private static final String TABLE_COUNTER= "count";
// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_AMOUNT = "amount";
private static final String[] COLUMNS = {KEY_ID,KEY_AMOUNT};
public void add(int counter){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_AMOUNT, counter); // get counter amount
// 3. insert
db.insert(TABLE_COUNTER, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
the logcat
15:08:30.713: D/AndroidRuntime(302): Shutting down VM
11-17 15:08:30.713: W/dalvikvm(302): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-17 15:08:30.742: E/AndroidRuntime(302): FATAL EXCEPTION: main
11-17 15:08:30.742: E/AndroidRuntime(302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdatabase/com.example.testdatabase.MainActivity}: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.os.Looper.loop(Looper.java:123)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-17 15:08:30.742: E/AndroidRuntime(302): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302): at java.lang.reflect.Method.invoke(Method.java:521)
11-17 15:08:30.742: E/AndroidRuntime(302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-17 15:08:30.742: E/AndroidRuntime(302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-17 15:08:30.742: E/AndroidRuntime(302): at dalvik.system.NativeStart.main(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302): Caused by: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302): at com.example.testdatabase.MainActivity.onCreate(MainActivity.java:49)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-17 15:08:30.742: E/AndroidRuntime(302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-17 15:08:30.742: E/AndroidRuntime(302): ... 11 more
any ideas?
Program throws an exception in :
save.setOnClickListener(new View.OnClickListener() ...
It seems that Button save is not initialized.
I'm trying to code a simple randomizer app. I had the randomizer button working, but then I changed some code (which I thought was irrelevant to the randomizer button) and it started crashing and getting the "IllegalStateException: Could not execute method of the activity" error. From what I can tell, this error is very specific to what the code is, because I could not find any answers that fit my code.
package com.example.randomgamechooser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void chooseGame (View view) {
GameList dbUtil = new GameList(this);
dbUtil.open();
String string = dbUtil.getRandomEntry();
//TextView textView = new TextView(this);
TextView textView = (TextView) findViewById(R.id.chosenbox);
textView.setTextSize(40);
textView.setText(string);
//setContentView (textView);
dbUtil.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
//starts the Game Selection activity
public void openGames (View view) {
Intent intent = new Intent(this, GameSelction.class);
startActivity(intent);
}
}
And this is the referenced GameList class
package com.example.randomgamechooser;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Random;
public class GameList {
private static final String TAG = "GameList";
//database name
private static final String DATABASE_NAME = "game_list";
//database version
private static final int DATABASE_VERSION = 1;
//table name
private static final String DATABASE_TABLE = "game_list";
//table columns
public static final String KEY_NAME = "name";
public static final String KEY_GENRE = "genre";
public static final String KEY_ROWID = "_id";
//database creation sql statement
private static final String CREATE_GAME_TABLE =
"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME +" text not null, " + KEY_GENRE + " text not null);";
//Context
private final Context mCtx;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
//Inner private class. Database Helper class for creating and updating database.
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// onCreate method is called for the 1st time when database doesn't exists.
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_GAME_TABLE);
db.execSQL(CREATE_GAME_TABLE);
}
//onUpgrade method is called when database version changes.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
}
//Constructor - takes the context to allow the database to be opened/created
//#param ctx the Context within which to work
public GameList(Context ctx) {
this.mCtx = ctx;
}
//This method is used for creating/opening connection
//#return instance of GameList
//#throws SQLException
public GameList open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
//This method is used for closing the connection.
public void close() {
mDbHelper.close();
}
//This method is used to create/insert new game.
//#param name
// #param genre
// #return long
public long createGame(String name, String genre) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_GENRE, genre);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
// This method will delete game.
// #param rowId
// #return boolean
public static boolean deleteGame(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// This method will return Cursor holding all the games.
// #return Cursor
public Cursor fetchAllGames() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_GENRE}, null, null, null, null, null);
}
// This method will return Cursor holding the specific game.
// #param id
// #return Cursor
// #throws SQLException
public Cursor fetchGame(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_GENRE}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public int getAllEntries()
{
Cursor cursor = mDb.rawQuery(
"SELECT COUNT(name) FROM game_list", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
//id = getAllEntries();
Random random = new Random();
int rand = random.nextInt(getAllEntries());
if(rand == 0)
++rand;
Cursor cursor = mDb.rawQuery(
"SELECT name FROM game_list WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
// This method will update game.
// #param id
// #param name
// #param standard
// #return boolean
public boolean updateGame(int id, String name, String standard) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_GENRE, standard);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
and here is the error log
07-31 14:50:45.215: D/AndroidRuntime(280): Shutting down VM
07-31 14:50:45.215: W/dalvikvm(280): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-31 14:50:45.236: E/AndroidRuntime(280): FATAL EXCEPTION: main
07-31 14:50:45.236: E/AndroidRuntime(280): java.lang.IllegalStateException: Could not execute method of the activity
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2072)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-31 14:50:45.236: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: java.lang.reflect.InvocationTargetException
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.MainScreen.chooseGame(MainScreen.java:23)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 14:50:45.236: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.view.View$1.onClick(View.java:2067)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 11 more
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Read the stacktrace carefuly. Answer is at the last "Caused by" exception;
07-31 14:50:45.236: E/AndroidRuntime(280): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
07-31 14:50:45.236: E/AndroidRuntime(280): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
07-31 14:50:45.236: E/AndroidRuntime(280): at com.example.randomgamechooser.GameList.getRandomEntry(GameList.java:153)
07-31 14:50:45.236: E/AndroidRuntime(280): ... 15 more
Query in method getRandomEntry() returns empty result, while you read from the first position.
I have an activity in which I am inserting values to a sqlite table, and then querying the table to get the values.
The activity:
public class TableActivity extends Activity {
TableLayout follow_up_table;
TableRow followup_tr_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
follow_up_table=(TableLayout) findViewById(R.id.follow_up_table);
//---------------Essay Title Table Header-----------------------------------------------
TableRow essay_title_tr_head = new TableRow(this);
essay_title_tr_head.setId(10);
essay_title_tr_head.setBackgroundResource(R.drawable.list_header);
essay_title_tr_head.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView label_essay_title = new TextView(this);
label_essay_title.setId(20);
label_essay_title.setText("Time");
label_essay_title.setTextColor(Color.WHITE);
label_essay_title.setPadding(5,5,5,5);
essay_title_tr_head.addView(label_essay_title);// add the column to the table row here
label_essay_title.setTextSize(12);
TextView label_description = new TextView(this);
label_description.setId(20);
label_description.setText("Student Name");
label_description.setTextColor(Color.WHITE);
label_description.setPadding(5,5,5,5);
essay_title_tr_head.addView(label_description);// add the column to the table row here
label_description.setTextSize(12);
follow_up_table.addView(essay_title_tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
//---------------Essay Title Table Header-----------------------------------------------
//getTime();
// database handler
insertData("Morning", "2013-04-23 10:00:00", "Suresh Kumar");
insertData("Morning", "2013-04-23 11:30:00", "Pravat Das");
insertData("Evening", "2013-04-23 16:16:00", "Namita Roy");
insertData("Evening", "2013-04-23 17:30:00", "Rakesh Mitra");
insertData("After noon", "2013-04-23 10:00:00", "Anil Sarma");
getTime();
}
public void getTime()
{
// database handler
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getTime();
Iterator itr = lables.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
//method to insert data into local database
public void insertData(String timeName, String time, String studentName)
{
DatabaseHandler db = new DatabaseHandler(TableActivity.this);
ContentValues values = new ContentValues();
//db.createDataBase();
values.put("timeName",timeName);
values.put("time",time);
values.put("studentName",studentName);
db.insertValues(timeName, time, studentName);
db.close();
}
}
The database helper class:
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "counselor";
// Labels table name
private static final String TABLE_LABELS = "follow_up";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_time_name = "time_name";
private static final String KEY_time = "time";
private static final String KEY_student_name = "student_name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE follow_up (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , time_name VARCHAR, time DATETIME, student_name VARCHAR)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
// Create tables again
onCreate(db);
}
public void insertValues(String timeName, String time, String studentName)
{
SQLiteDatabase db = this.getWritableDatabase();
String sql = "INSERT INTO follow_up ( time_name, time, student_name) VALUES ('"+timeName+"', '"+time+"', '"+studentName+"')";
Cursor cursor = db.rawQuery(sql, null); //<< execute here
cursor.moveToFirst();
db.close();
}
//
// /**
// * Getting all labels
// * returns list of labels
// * */
public List<String> getTime(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT time_name FROM follow_up ORDER BY time";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
The error in logcat:
04-24 09:21:18.187: D/dalvikvm(1260): GC_FOR_ALLOC freed 66K, 7% free 2561K/2748K, paused 169ms, total 183ms
04-24 09:21:18.207: I/dalvikvm-heap(1260): Grow heap (frag case) to 3.222MB for 635812-byte allocation
04-24 09:21:18.328: D/dalvikvm(1260): GC_FOR_ALLOC freed 2K, 6% free 3179K/3372K, paused 116ms, total 116ms
04-24 09:21:18.467: D/dalvikvm(1260): GC_CONCURRENT freed <1K, 6% free 3190K/3372K, paused 9ms+27ms, total 141ms
04-24 09:21:19.167: E/CursorWindow(1260): Failed to read row 0, column 1 from a CursorWindow which has 5 rows, 1 columns.
04-24 09:21:19.167: D/AndroidRuntime(1260): Shutting down VM
04-24 09:21:19.167: W/dalvikvm(1260): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-24 09:21:19.197: E/AndroidRuntime(1260): FATAL EXCEPTION: main
04-24 09:21:19.197: E/AndroidRuntime(1260): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ica.dynamictable/com.ica.dynamictable.TableActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.os.Looper.loop(Looper.java:137)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-24 09:21:19.197: E/AndroidRuntime(1260): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): at java.lang.reflect.Method.invoke(Method.java:511)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-24 09:21:19.197: E/AndroidRuntime(1260): at dalvik.system.NativeStart.main(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.CursorWindow.nativeGetString(Native Method)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.CursorWindow.getString(CursorWindow.java:434)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.commons.DatabaseHandler.getTime(DatabaseHandler.java:77)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.dynamictable.TableActivity.getTime(TableActivity.java:83)
04-24 09:21:19.197: E/AndroidRuntime(1260): at com.ica.dynamictable.TableActivity.onCreate(TableActivity.java:73)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.Activity.performCreate(Activity.java:5104)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-24 09:21:19.197: E/AndroidRuntime(1260): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-24 09:21:19.197: E/AndroidRuntime(1260): ... 11 more
Actually what I am trying to do is to put all time_name into a list so that I can populate a table using it.
Where am I going wrong?
In your method of DBHelper getTime(), you are using query for getting only one row. Later in that method you are using labels.add(cursor.getString(1));
you should use labels.add(cursor.getString(0)); instead because there is only one row in the Cursor
cursor.getString(1) should be cursor.getString(0) because in query "SELECT time_name FROM follow_up ORDER BY time"; you will get only one data i.e. time_name at index 0 in cursor.getString(0)
SELECT time_name FROM follow_up ORDER BY time
contains only 1 column. Its index is therefore 0. You'd access it with
labels.add(cursor.getString(0));
Or, more cleanly :
int index = cursor.getColumnIndex("time_name");
and
labels.add(cursor.getString(index));
Also, I should add that your if ... do ... while can be replaced by a single while(cursor.moveToNext()) block, as the position of the newly created cursor is always right before first, making the first moveToNext effetively identical to a moveToFirst
i have a problem with my SQLite class. In fact, i was learning how to setting up (update and read) a database on android and I successfully wrote on the database, but when i try to read the informations and display them on the screen, my application just crashes.
I searched the problem and found that the cause of the crash is the Cursor. I commented the cursor's method, so if someone can help me with that, i would be thankful.
This my Database class.
package com.example.sqlprogramming;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "person_name";
public static final String KEY_RATE = "person_rate";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 2;
private Dhelper ourHelperdb;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class Dhelper extends SQLiteOpenHelper{
public Dhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + "VARCHAR NOT NULL, " +
KEY_RATE + "VARCHAR NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseClass(Context c){
ourContext = c;
}
public DatabaseClass open() throws SQLException{
ourHelperdb = new Dhelper(ourContext);
ourDatabase = ourHelperdb.getWritableDatabase();
return this;
}
public void close(){
ourHelperdb.close();
}
public long addEntry(String personName, String personHotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, personName);
cv.put(KEY_RATE, personHotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
//HERE IS MY PROBLEM WITH THE CURSOR
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_RATE};
String result = "hello";
Cursor c = ourDatabase.query(true, DATABASE_TABLE, columns, null, null, null, null, null, null);
int iRowId = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(KEY_RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRowId) + " " + c.getString(iName) +" " + c.getString(iRate) + "\n";
}
c.close();
return result;
}
}
And this Class call the Database Class and should take informations from database to display it on the screen.
package com.example.sqlprogramming;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sqlview);
TextView textInfo = (TextView) findViewById (R.id.tvSQLinfo);
DatabaseClass info = new DatabaseClass(this);
info.open();
String _data = info.getData();
info.close();
textInfo.setText(_data);
}
}
Thank you again.
I'll post stacktrace and logcat soon.
Here is my Logcat/Stacktrace
02-24 20:08:12.378: E/Curosr!(1221): I got an error here :
02-24 20:08:12.378: E/Curosr!(1221): android.database.sqlite.SQLiteException: no such column: person_name (code 1): , while compiling: SELECT _id AS _id, person_name, person_rate FROM peopleTable
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.DatabaseClass.getData(DatabaseClass.java:75)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.SQLview.onCreate(SQLview.java:14)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Activity.performCreate(Activity.java:5104)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Looper.loop(Looper.java:137)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 20:08:12.378: E/Curosr!(1221): at dalvik.system.NativeStart.main(Native Method)
Your create statement is missing a few spaces. Try using:
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " VARCHAR NOT NULL, " +
KEY_RATE + " VARCHAR NOT NULL);");
According to your current statement, your last two column names become person_nameVARCHAR and person_rateVARCHAR
If you're reading, you need to use:
ourDatabase = ourHelperdb.getReadableDatabase();
When you open your DB, you are setting it to write.
(That's my first guess, post stack trace).
Here's a working example from some of my code on how to read a cursor:
mDb = mDbHelper.getReadableDatabase();
Cursor c = mDb.query("Timesheets", new String[] {
KEY_TIMESHEETS_ROWID + " AS _id", KEY_TIMESHEETS_DESCRIPTION,
KEY_TIMESHEETS_TITLE, KEY_TIMESHEETS_DATE_START,
KEY_TIMESHEETS_DATE_END, KEY_TIMESHEETS_INVOICED,
KEY_TIMESHEETS_PROJECTID }, "timesheet_id = ?",
new String[] { String.valueOf(timesheetId) }, null, null, null);
c.moveToFirst();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timesheet timesheet = new Timesheet();
while (c.isAfterLast() == false) {
timesheet.setTimesheetId(c.getInt(0));
// ...
c.moveToNext();
}
c.close();