My app is supposed to save data in a database then display it in a listView.
Problem is that the listView doesn't display anything.
Looking through the error log it seems to say that it has problem saving the data.
Thanks in advance
DBAdapter
package se.welovecode.wdmmg;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TRANSACTIONS = "transactions";
public static final String KEY_ITEM = "item";
public static final String KEY_SUM = "sum";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TRANSACTIONS, KEY_ITEM, KEY_SUM,};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TRANSACTIONS = 1;
public static final int COL_ITEM = 2;
public static final int COL_SUM = 3;
// DataBase info:
public static final String DATABASE_NAME = "db";
public static final String DATABASE_TABLE = "mainTransactions";
public static final int DATABASE_VERSION = 1; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TRANSACTIONS + " TEXT NOT NULL, "
+ KEY_ITEM + " TEXT NOT NULL, "
+ KEY_SUM + " INTEGER"
+ ");";
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
Context context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String transactions) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TRANSACTIONS, transactions);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertRow2(String item) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertRow3(int sum) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_SUM, sum);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String transaction, String item, String sum) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TRANSACTIONS, transaction);
newValues.put(KEY_ITEM, item);
newValues.put(KEY_SUM, sum);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity
package se.welovecode.wdmmg;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
DBAdapter myDB;
TextView Balance;
Double value;
ListView lwTransactions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Balance = (TextView) findViewById(R.id.tvBalance);
refreshSum();
openDB();
populateListView();
}
#Override
protected void onResume() {
super.onResume();
refreshSum();
populateListView();
}
protected void onDestroy(){
super.onDestroy();
closeDb();
}
private void openDB(){
myDB = new DBAdapter(this);
myDB.open();
}
private void closeDb(){
myDB.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_add:
Intent intent = new Intent(MainActivity.this, AddTransaction.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
private void refreshSum(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
value = (double) prefs.getFloat("KEY", 0f);
Balance.setText(value.toString());
}
private void populateListView(){
Cursor cursor = myDB.getAllRows();
String[] fromFieldNames = new String[]{DBAdapter.KEY_ROWID, DBAdapter.KEY_TRANSACTIONS, DBAdapter.KEY_ITEM, DBAdapter.KEY_SUM,};
int[] toViewIDs = new int[] {R.id.textViewRowID, R.id.textViewStore, R.id.textViewService, R.id.textViewCost};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor, fromFieldNames,toViewIDs,0);
lwTransactions = (ListView) findViewById(R.id.lwTransactions);
lwTransactions.setAdapter(myCursorAdapter);
}
}
Errorlog
06-12 17:33:38.383 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 7 in [INSERT INTO mainTransactions(transactions) VALUES (?)]: NOT NULL constraint failed: mainTransactions.item
06-12 17:33:38.383 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting transactions=hsns
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.item (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow(DBAdapter.java:68)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:55)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 6 in [INSERT INTO mainTransactions(item) VALUES (?)]: NOT NULL constraint failed: mainTransactions.transactions
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting item=bsb
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.transactions (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow2(DBAdapter.java:76)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:58)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteLog﹕ (1299) abort at 6 in [INSERT INTO mainTransactions(sum) VALUES (?)]: NOT NULL constraint failed: mainTransactions.transactions
06-12 17:33:38.393 29168-29168/se.welovecode.wdmmg E/SQLiteDatabase﹕ Error inserting sum=120
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: mainTransactions.transactions (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1595)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1465)
at se.welovecode.wdmmg.DBAdapter.insertRow3(DBAdapter.java:83)
at se.welovecode.wdmmg.AddTransaction.onClick_AddTransaction(AddTransaction.java:61)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4268)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
U got KEY_TRANSACTIONS TEXT NOT NULL and KEY_ITEM TEXT NOT NULL
but u pass in insertRow only KEY_TRANSACTION but u need to put KEY_ITEM also
public long insertRow(String transactions) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TRANSACTIONS, transactions);
initialValues.put(KEY_ITEM, "some key item");
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
or remove NOT NULL from your KEY_ITEM column constraints
Related
I have got stuck in the above-mentioned error message in Android Studio. My Database is a simple one
1st column: Name TEXT PRIMARY KEY
2nd column: Price TEXT
I have already gone through the answers to the same question in StackOverflow but couldn't resolve the error.
I am quoting my DataBaseHelper class and insertActivity here:
private static final String DATABASE_NAME = "ItemDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "Items";
private static final String COLUMN_NAME = "Name";
private static final String COLUMN_PRICE = "Price";
DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "(" + COLUMN_NAME + " TEXT NOT NULL PRIMARY KEY, " + COLUMN_PRICE + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
boolean addItem(String itemName, String itemPrice) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, itemName);
contentValues.put(COLUMN_PRICE, itemPrice);
SQLiteDatabase db = this.getWritableDatabase();
boolean b = db.insert(TABLE_NAME, null, contentValues) != -1;
db.close();
return b;
}
Cursor getPrice(String itemName) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" SELECT Price FROM Items WHERE Name= ? ", new String[]{itemName});
}
Cursor updatePrice(String itemName, String itemPrice)
{
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" UPDATE Items SET Price= ? WHERE Name= ? ", new String[]{itemPrice,itemName});
}
public List<String> getName(){
List<String> list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
}
public class insertActivity extends AppCompatActivity {
EditText itemName,itemPrice;
Button buttonInsert;
boolean b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
itemName= findViewById(R.id.itemName);
itemPrice= findViewById(R.id.itemPrice);
buttonInsert=findViewById(R.id.buttonInsert);
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
final DataBaseHelper dataBaseHelper =new DataBaseHelper(getApplicationContext());
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
b = dataBaseHelper.addItem(Name,Price);
}catch (Exception e)
{
e.printStackTrace();
}
if( b )
{
Toast.makeText(getApplicationContext(),"Item Inserted Successfully ",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(),"Item Insertion Failed ",Toast.LENGTH_SHORT).show();
}
});
}
}
error:
W/System.err: at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:746)
W/System.err: at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.anirbit.anirbitadak.nirman.DataBaseHelper.addItem(DataBaseHelper.java:45)
W/System.err: at com.anirbit.anirbitadak.nirman.insertActivity$1.onClick(insertActivity.java:39)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25881)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)```
These lines:
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
assign to the variables Name and Price the text of the EditTexts itemName and itemPrice when the insertActivity loads (maybe they are just empty strings) and they are never changed.
So when you click the button the listener by calling dataBaseHelper.addItem(Name,Price) tries to insert the same values in the table and this results to the error you get because since the column Name is the Primary Key of the table it must be unique.
What you must do is move these lines inside the listener:
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
try {
................................................
}
so when you click the button the correct values are retrieved from the EditTexts and then inserted in the table.
I'm not entirely sure what could be happening, I know that there is a mismatch when I try to insert, but when I double check my code I can't see why it would spit that error out. I am simply trying to insert a username and password (both are Strings).
CONTEXT:
In my RegisterLoginActivity.java I made it when the user taps the TextView "Create account" it will grab the username and password and turn them into strings.
Then in my DatabaseOperations.java I use the function putInformation() to insert the data.
My TableData.java simply contains my table information.
RegisterLoginActivity.java;
package com.example.envy.energyvue;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterLoginActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS;
TextView REG;
String user_name, user_pass;
Context ctx = this;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
//getActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_login);
USER_NAME = (EditText) findViewById(R.id.userText);
USER_PASS = (EditText) findViewById(R.id.passText);
REG = (TextView) findViewById(R.id.createAccount);
REG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB,user_name, user_pass);
}
});
// IGNORE THIS PORTION, IT IS FOR LOGGING IN AFTER I REGISTER
//********************************************
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_NAME.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
Cursor CR = DB.getInformation(DB);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do{
if(user_name.equals(CR.getString(0)) && user_pass.equals(CR.getString(1))){
loginstatus = true;
}
}while(CR.moveToFirst());
if(loginstatus){
Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
DatabaseOperations.java;
package com.example.envy.energyvue;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Envy on 7/13/2016.
*
* private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
*/
public class DatabaseOperations extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserData.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME;
public DatabaseOperations(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void putInformation(DatabaseOperations dop, String user_id, String password){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.COLUMN_NAME_USER_ID, user_id);
cv.put(TableData.TableInfo.COLUMN_NAME_PASSWORD, password);
System.out.print("LOLOLSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
long newRowId;
newRowId = SQ.insert(
TableData.TableInfo.TABLE_NAME,
null,
cv);
}
public Cursor getInformation(DatabaseOperations dop){
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] projection = {
TableData.TableInfo._ID,
TableData.TableInfo.COLUMN_NAME_USER_ID,
TableData.TableInfo.COLUMN_NAME_PASSWORD
};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, projection, null, null, null, null, null);
return CR;
}
}
TableData.java;
package com.example.envy.energyvue;
import android.provider.BaseColumns;
/**
* Created by Envy on 7/13/2016.
*/
public class TableData {
public TableData(){}
public static abstract class TableInfo implements BaseColumns {
public static final String TABLE_NAME = "login_information";
public static final String COLUMN_NAME_USER_ID = "user_id";
public static final String COLUMN_NAME_PASSWORD = "password";
}
}
Error:
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteLog: (20) statement aborts at 5: [INSERT INTO login_information(password,user_id) VALUES (?,?)] datatype mismatch
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteDatabase: Error inserting password= bbb user_id=bbb
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
#################################################################
Error Code : 20 (SQLITE_MISMATCH)
Caused By : Data type mismatch.
(datatype mismatch (code 20))
#################################################################
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1609)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.envy.energyvue.DatabaseOperations.putInformation(DatabaseOperations.java:59)
at com.example.envy.energyvue.RegisterLoginActivity$1.onClick(RegisterLoginActivity.java:37)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Alright guys.. after many hours, I figured it out ....I put my database name with a ".db" extension which was messing things up.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I have looked through SO and found many people having this same error, but they seem to be forgetting to add the column into the create statement or missing whitespace, neither of which I believe I did.
My logcat is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmd.referenceapplication, PID: 31988
android.database.sqlite.SQLiteException: no such column: QUANTITY (code 1): , while compiling: SELECT * FROM FTS WHERE (QUANTITY MATCH ?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.gmd.referenceapplication.DatabaseTable.query(DatabaseTable.java:187)
at com.gmd.referenceapplication.DatabaseTable.getWordMatches(DatabaseTable.java:179)
at com.gmd.referenceapplication.SearchableActivity$1.onQueryTextChange(SearchableActivity.java:70)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7991)
at android.widget.TextView.handleTextChanged(TextView.java:8053)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10157)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1033)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:559)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:491)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
DatabaseTable class:
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTITY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
public static final String _id = "_id";
//name, tbale name, version
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
private final Context mcontext;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
mcontext = context;
}
private class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private final MyDataProvider dp = new MyDataProvider(mcontext);
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +_id+ " INTEGER PRIMARY KEY,"+
COL_QUANTITY + " TEXT, " +
COL_VALUE + " TEXT," +
COL_UNCERTAINTY + " TEXT," +
COL_UNIT + " TEXT " + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
loadConstants();
Log.e("Database Operation", "DatabaseOpenHelper constructor called, constants loaded?");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#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 " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
public SQLiteDatabase getmDatabase(){
return mDatabase;
}
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
HashMap map = dp.getAllMap();
Iterator<Map.Entry<String, ListViewItem>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, ListViewItem> entry = entries.next();
Log.d("thing:", entry.getKey());
//addConstant(entry.getKey(), entry.getValue(), entry.getUncertainty(), entry.getUnit());
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
return db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
//database openhelper ends
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
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;
}
public Cursor getAllTitles(){
return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
COL_QUANTITY,
COL_UNCERTAINTY,
COL_UNIT,
COL_VALUE},
null,
null,
null,
null,
null);
}
Thank you to anyone who can tell me why it is telling me the column "QUANTITY" is not being created, I really don't know.
If you change the schema you should increment DATABASE_VERSION so the database is upgraded.
Error is cursor index out of bounds exception, cursor is empty, receiving nothing.
Here is logcat:
FATAL EXCEPTION: main: com.example.root.notebook, PID:
.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.root.notebook.NotebookDbAdapter.cursorToNote(NotebookDbAdapter.java:101)
at com.example.root.notebook.NotebookDbAdapter.createNote(NotebookDbAdapter.java:67)
at com.example.root.notebook.NoteEditFragment$4.onClick(NoteEditFragment.java:160)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
NotebookDbAdapter.java
package com.example.root.notebook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.Calendar;
/**
* Created by root on 28/04/2016.
*/
public class NotebookDbAdapter {
private static final String DATABASE_NAME="notebook.db";
private static final int DATABASE_VERSION=1;
public static final String NOTE_TABLE="note";
public static final String COLUMN_ID="_id";
public static final String COLUMN_TITLE="title";
public static final String COLUMN_MESSAGE="message";
public static final String COLUMN_CATEGORY="category";
public static final String COLUMN_DATE="date";
public String[] allColumns={COLUMN_ID, COLUMN_TITLE, COLUMN_MESSAGE, COLUMN_CATEGORY, COLUMN_DATE};
public static final String CREATE_TABLE_NOTE= " create table " + NOTE_TABLE + " ( "
+ COLUMN_ID +" integer primary key autoincrement, "
+COLUMN_TITLE +" text not null, "
+COLUMN_MESSAGE+ " text not null, "
+COLUMN_CATEGORY+" integer not null, "
+COLUMN_DATE+" ); ";
private SQLiteDatabase sqlDB;
private NotebookDbHelper notebookDbHelper;
private Context context;
public NotebookDbAdapter (Context ctx){
context=ctx;
}
public NotebookDbAdapter open() throws android.database.SQLException{
notebookDbHelper=new NotebookDbHelper(context);
sqlDB=notebookDbHelper.getWritableDatabase();
return this;
}
public void close(){
notebookDbHelper.close();
}
public Note createNote(String title,String message,Note.Category category){
ContentValues values=new ContentValues();
values.put(COLUMN_TITLE,title);
values.put(COLUMN_MESSAGE,message);
values.put(COLUMN_CATEGORY,category.name());
values.put(COLUMN_DATE, Calendar.getInstance().getTimeInMillis() + "");
long insertId=sqlDB.insert(NOTE_TABLE,null,values);
Cursor cursor=sqlDB.query(NOTE_TABLE,allColumns, COLUMN_ID + " = " + insertId , null, null, null, null);
cursor.moveToFirst();
Note newNote=cursorToNote(cursor);
cursor.close();
return newNote;
}
public long deleteNote(long idToDelete){
return sqlDB.delete(NOTE_TABLE,COLUMN_ID +" = "+idToDelete ,null);
}
public long updateNote(long idToUpdate,String newTitle,String newMessage,Note.Category newCategory){
ContentValues values=new ContentValues();
values.put(COLUMN_TITLE,newTitle);
values.put(COLUMN_MESSAGE,newMessage);
values.put(COLUMN_CATEGORY,newCategory.name());
values.put(COLUMN_DATE, Calendar.getInstance().getTimeInMillis() + "");
return sqlDB.update(NOTE_TABLE, values ,COLUMN_ID + " = " + idToUpdate, null);
}
public ArrayList<Note> getAllnotes(){
ArrayList<Note> notes=new ArrayList<Note>();
Cursor cursor=sqlDB.query(NOTE_TABLE,allColumns, null ,null ,null ,null ,null);
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()){
Note note=cursorToNote(cursor);
notes.add(note);
}
cursor.close();
return notes;
}
private Note cursorToNote(Cursor cursor){
Note newNote=new Note(cursor.getString(1),cursor.getString(2), Note.Category.valueOf(cursor.getString(3)),
cursor.getLong(0),cursor.getLong(4));
return newNote;
}
private static class NotebookDbHelper extends SQLiteOpenHelper{
NotebookDbHelper(Context ctx){
super(ctx,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE_NOTE);
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
Log.w(NotebookDbHelper.class.getName(),"upgrading database from version "+ newVersion+"to"+oldVersion+",which will destroy all old data");
db.execSQL("Drop table if exist "+ NOTE_TABLE);
onCreate(db);
}
}
}
Replace your below code
cursor.moveToFirst();
Note newNote=cursorToNote(cursor);
cursor.close();
return newNote;
With
if (cursor != null && cursor.moveToFirst()) {
Note newNote=cursorToNote(cursor);
cursor.close();
return newNote;
}
else {
return null;
}
Try this :
public ArrayList<Note> getAllnotes(){
ArrayList<Note> notes=new ArrayList<Note>();
Cursor cursor = sqlDB.rawQuery("SELECT * FROM " + NOTE_TABLE, null);
if(cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Note note=new Note(cursor.getString(1),cursor.getString(2), Note.Category.valueOf(cursor.getString(3)), cursor.getLong(0),cursor.getLong(4));
notes.add(note);
} while (cursor.moveToNext());
}
}
cursor.close();
return notes;
}
I am getting the following error: no such table: categories (code 1): , while compiling: SELECT * FROM categories.
I have an activity, SplashActivity which loads a second activity Category. On the Category Activity, I am loading a spinner with data from a table [categories] in the database. When the user selects an item on the spinner and it should load a QuestionsActivity which shows questions from the database based on the selection on the spinner.
The database is being copied from the Assets folder. It was working and then suddenly the error started popping up when I put the code to load the Question activity on the 'play' button. I have uninstalled the application from my phone to wipe of the data and reloading still gives the same error.
I have looked here and here, still no luck getting it to work.
This is my logcat
06-17 21:15:16.610 16854-16854/zw.co.pindula.funsa E/SQLiteLog﹕ (1) no such table: categories
06-17 21:15:16.624 16854-16854/zw.co.pindula.funsa E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: zw.co.pindula.funsa, PID: 16854
java.lang.RuntimeException: Unable to start activity ComponentInfo{zw.co.pindula.funsa/zw.co.pindula.funsa.util.Category}: android.database.sqlite.SQLiteException: no such table: categories (code 1): , while compiling: SELECT * FROM categories
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: categories (code 1): , while compiling: SELECT * FROM categories
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at zw.co.pindula.funsa.db.DBHelper.getAllCategories(DBHelper.java:168)
at zw.co.pindula.funsa.util.Category.loadCategoryData(Category.java:70)
at zw.co.pindula.funsa.util.Category.onCreate(Category.java:37)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is my DBHelper Class
package zw.co.pindula.funsa.db;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import zw.co.pindula.funsa.quiz.Question;
/**
* Created by NKT on 03/06/2015.
*/
public class DBHelper extends SQLiteOpenHelper{
private static String DB_PATH;// = "/data/data/zw.co.pindula.funsa/databases/";
// Database Version
private static final int DATABASE_VERSION = 1;
private static String DB_NAME = "questionsDb";
//Category Table name
private static final String TABLE_CATEGORY = "categories";
private final Context myContext;
//private static String DB_PATH= Context.getDatabasePath(DB_NAME).getPath();
private SQLiteDatabase myDataBase;
public DBHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.myContext = context;
DB_PATH = myContext.getDatabasePath(DB_NAME).getPath();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(!dbExist)
{
//By calling this method an empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
/*
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH;// + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database doesn't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
*/
//New checkDataBase method
boolean checkdb = false;
try{
String myPath = myContext.getFilesDir().getAbsolutePath().replace("files", "databases")+ File.separator + DB_NAME;
File dbfile = new File(myPath);
checkdb = dbfile.exists();
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;// + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH;// + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
//db.execSQL("DROP D IF EXISTS " + TABLE);
// Create tables again
//onCreate(db);
}
public List<Question> getQuestionSet(int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty +
" ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}
/**
* Getting and return all the Categories
* */
public List<String> getAllCategories(){
List<String> myCategories = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
myCategories.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning categories
return myCategories;
}
/*
* This method sets the questions using the categories
*/
public List<Question> getQuestionSetCategories(String cat, int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE CATEGORY=" + cat +
" ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}
}
This is the Category Activity
package zw.co.pindula.funsa.util;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import zw.co.pindula.funsa.R;
import zw.co.pindula.funsa.db.DBHelper;
import zw.co.pindula.funsa.quiz.Constants;
import zw.co.pindula.funsa.quiz.GamePlay;
import zw.co.pindula.funsa.quiz.Question;
public class Category extends Activity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
String theCategory; //This is the String to hold the selected category
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
spinner = (Spinner)findViewById(R.id.mySpinner);
loadCategoryData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadCategoryData() {
// database handler
DBHelper db = new DBHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllCategories();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void startGame(View view){
Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
theCategory = spinner.getSelectedItem().toString();
if(theCategory==null){
Toast.makeText(this, "You didn't select anything: ",
Toast.LENGTH_SHORT).show();
}
else
{
Intent i;
List<Question> questions = getQuestionSetFromDb();
//Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((FunsaApplication)getApplication()).setCurrentGame(c);
//Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
startActivityForResult(i, Constants.PLAYBUTTON);
//break;
}
}
private List<Question> getQuestionSetFromDb() throws Error {
int diff = getDifficultySettings();
int numQuestions = getNumQuestions();
DBHelper myDbHelper = new DBHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
List<Question> questions = myDbHelper.getQuestionSetCategories(theCategory, diff, numQuestions);
myDbHelper.close();
return questions;
}
/**
* Method to return the difficulty settings
* #return
*/
private int getDifficultySettings() {
SharedPreferences settings = getSharedPreferences(Constants.SETTINGS, 0);
int diff = settings.getInt(Constants.DIFFICULTY, Constants.MEDIUM);
return diff;
}
/**
* Method to return the number of questions for the game
* #return
*/
private int getNumQuestions() {
SharedPreferences settings = getSharedPreferences(Constants.SETTINGS, 0);
int numRounds = settings.getInt(Constants.NUM_ROUNDS, 2); //This sets the number of rounds
return numRounds;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selection =adapterView.getItemAtPosition(i).toString();//.getItemAtPosition(i).toString();
theCategory = selection;
// Showing selected spinner item
Toast.makeText(adapterView.getContext(), "You selected: " + selection,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}