SQLite with android error - java

i am relatively new to programming and android,and i am working on a little notepad app. I learned how to use SQLite from a tutorial on the web,but something is wrong..when i am running the app,it keeps telling me that there are no columns in the name... but there are! what am i doing wrong? i checked the syntax a dozens of times,and i did it like the tutorial did one by one. I know this question was here before more than one time,but when reading the answers, i still couldnt find a solution to my specific problem. basically i just added 2 notes with title and text and wanted to present them in the main activity in a ListView,but nothing is showing up because of the database problem.
Help is very very appreciated :) thx in advance
this is the classes:
import java.util.ArrayList;
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;
public class DatabaseManager extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "notesDb";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "notes";
private static final String NOTE_ID = "_id";
private static final String NOTE_TITLE = "title";
private static final String NOTE_TEXT = "text";
private static final String NOTE_CREATION_DATE = "creationDate";
public DatabaseManager(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NAME+"(" + NOTE_ID +" INTEGER PRIMARY KEY,"+ NOTE_TITLE + "TEXT,"
+ NOTE_TEXT + "TEXT," + NOTE_CREATION_DATE + "TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public void addNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NOTE_TITLE, note.getTitle());
values.put(NOTE_TEXT, note.getText());
values.put(NOTE_CREATION_DATE, note.getCurrentTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void deleteNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, NOTE_ID + "?=",new String[]{String.valueOf(note.getId())} );
db.close();
}
public String[] listNotes(){
ArrayList<String> tempArray = new ArrayList<String>();
String[]notesArray = new String[0];
String sqlQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(sqlQuery,null);
if(c.moveToFirst()){
do{
tempArray.add(c.getString(c.getColumnIndex(NOTE_TITLE)));
}
while(c.moveToNext());
}
c.close();
notesArray = tempArray.toArray(notesArray);
return notesArray;
}
}
the note object:
import java.util.Calendar;
public class Note {
private int id;
private String text;
private String title;
private String creationTime;
private String currentTime;
public Note(){
}
public String getCurrentTime(){
return getDayOfMonth()+"/"+getMonth()+"/"+getYear()+" "+getDay()+", "+getHour()+":"+getMinutes();
}
public String getMonth(){
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
String month = new String();
switch(currentMonth){
case 0:
month = "01";
break;
case 1:
month = "02";
break;
case 3:
month = "04";
break;
case 4:
month = "05";
break;
case 5:
month = "06";
break;
case 6:
month = "07";
break;
case 7:
month = "08";
break;
case 8:
month = "09";
break;
case 9:
month = "10";
break;
case 10:
month = "11";
break;
case 11:
month = "12";
break;
}
return month;
}
public String getDayOfMonth(){
int currentDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
String dayOfMonth = new String();
if(currentDayOfMonth<10){
dayOfMonth = "0"+currentDayOfMonth;
}
else{
dayOfMonth = ""+currentDayOfMonth;
}
return dayOfMonth;
}
public String getYear(){
String year = ""+Calendar.getInstance().get(Calendar.YEAR);
return year;
}
public String getDay(){
int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
String day = new String();
switch(currentDay){
case 1:
day = "Sun";
break;
case 2:
day = "Mon";
break;
case 3:
day = "Tue";
break;
case 4:
day = "Wed";
break;
case 5:
day = "Thu";
break;
case 6:
day = "Fri";
break;
case 7:
day = "Sat";
break;
}
return day;
}
public String getHour(){
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
String hour = new String();
if(currentHour<10){
hour = "0"+currentHour;
}
else{
hour = ""+currentHour;
}
return hour;
}
public String getMinutes(){
int currentMinutes = Calendar.getInstance().get(Calendar.MINUTE);
String minutes = new String();
if(currentMinutes<10){
minutes = "0"+currentMinutes;
}
else{
minutes = ""+currentMinutes;
}
return minutes;
}
public void setText(String text){
this.text = text;
}
public String getText(){
return this.text;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}
the main activity:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseManager db = new DatabaseManager(this);
Note n1 = new Note();
Note n2 = new Note();
n1.setTitle("n1 title");
n1.setText("n1 text");
n2.setTitle("n2 title");
n2.setText("n2 text");
db.addNote(n1);
db.addNote(n2);
String[]notes = db.listNotes();
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notes);
ListView lv = (ListView)findViewById(R.id.notes_list);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/board"
android:scaleType="fitXY"/>
<ImageButton
android:id="#+id/add_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:src="#drawable/note"
android:background="#android:color/transparent"/>
<ListView
android:id="#+id/notes_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"/>

A semi colon inside the query is missing for your table creation string CREATE_NOTES_TABLE string. Include a semicolon (;) inside the string just after the final ")"; ie. Make it ");";

Related

Data is not getting saved in the database using sqlite database in android studio

I am a beginner in android development. I am making a keyboard app in android studio using java. I want to store the data whatever is being typed in database. I am able to get whatever is typed. I tried to store in the database. But its not getting saved there. Maybe I am not calling the database class properly. Please correct me where I am going wrong.
Link for complete code including the XML files etc
This is the code for the keyboard from which the database is called
package com.example.keyboard;
import android.annotation.SuppressLint;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.media.AudioManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputConnection;
import android.widget.Toast;
public class EDMTKeyboard extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
private KeyboardView kv;
private Keyboard keyboard;
private boolean isCaps = false;
String str="";
String app;
String app2;
DBHelper DB;
//Press Ctrl+O
#SuppressLint("InflateParams")
#Override
public View onCreateInputView() {
kv = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard,null);
keyboard = new Keyboard(this,R.xml.qwerty);
kv.setKeyboard(keyboard);
kv.setOnKeyboardActionListener(this);
DB = new DBHelper(this);
return kv;
}
#Override
public void onPress(int i) {
}
#Override
public void onRelease(int i) {
}
#Override
public void onKey(int i, int[] ints) {
InputConnection ic = getCurrentInputConnection();
playClick(i);
switch (i)
{
case Keyboard.KEYCODE_DELETE:
ic.deleteSurroundingText(1,0);
StringBuffer sb= new StringBuffer(str);
if(sb.length() != 0) {
sb.deleteCharAt(sb.length()-1); }
str = new String(sb);
break;
case Keyboard.KEYCODE_SHIFT:
isCaps = !isCaps;
keyboard.setShifted(isCaps);
kv.invalidateAllKeys();
break;
case Keyboard.KEYCODE_DONE:
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENTER));
app="App Name";
app2="App name2";
Boolean checkinsertdata = DB.insertuserdata(app,str);
Toast.makeText(EDMTKeyboard.this, str, Toast.LENGTH_SHORT).show();
str="";
break;
//if(checkinsertdata==true)
// Toast.makeText(EDMTKeyboard.this, "New Entry Inserted", Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(EDMTKeyboard.this, "New Entry Not Inserted", Toast.LENGTH_SHORT).show();
default:
char code = (char)i;
char dup;
if(Character.isLetter(code) && isCaps)
code = Character.toUpperCase(code);
//if(str.length()==0)
//{ dup = code;
// str = Character.toString(dup);}
//else
str = str + code;
ic.commitText(String.valueOf(code),1);
}
}
private void playClick(int i) {
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
switch(i)
{
case 32:
am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR);
break;
case Keyboard.KEYCODE_DONE:
case 10:
am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN);
break;
case Keyboard.KEYCODE_DELETE:
am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE);
break;
default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD);
}
}
#Override
public void onText(CharSequence charSequence) {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeDown() {
}
#Override
public void swipeUp() {
}
}
This is the database class
package com.example.keyboard;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database_name.db";
private static final String TABLE_NAME = "table_name";
DBHelper(Context context)
{
super(context,DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable= "create table " + TABLE_NAME + "( appname TEXT PRIMARY KEY, data TEXT )";
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("drop Table if exists " + TABLE_NAME);
onCreate(DB);
}
public Boolean insertuserdata(String app, String str)
{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("APPNAME", app);
contentValues.put("DATA", str);
long result=DB.insert(TABLE_NAME, null, contentValues);
if(result==-1){
return false;
}else{
return true;
}
}
}
The DB.insert() function returns true but the data is not getting saved. Please guide me where I am going wrong.
Change
contentValues.put("APPNAME", app);
contentValues.put("DATA", str);
To
contentValues.put("appname", app);
contentValues.put("data", str);

SQL database in android , Index -1 requested with size 0

I have been working on an android app which requires to retrieve some information from the SQL database. Initially I was trying to do that form a function named getRemainingAmount() in databaseHelper1 class but that caused an error
FATAL EXCEPTION: main Process: com.carrot.wallet, PID: 30591 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment at
After that when I tried to ritrive data from the addTransaction class then I started getting the folowing error:
2020-05-30 09:25:12.946 11239-11239/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carrot.wallet, PID: 11239
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.carrot.wallet.AddTransaction$4.onClick(AddTransaction.java:102)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is my databaseHeleper1 class which contains the function getRemainingAmount()
package com.carrot.wallet.Database;
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 androidx.annotation.Nullable;
public class DatabaseHelper1 extends SQLiteOpenHelper {
private static final int version = 3;
private static final String name = "YEAR_DETAILS";
private static final String COL0 = "YEAR";
private static final String COL1 = "MONTH";
private static final String COL2 = "SPENT";
private static final String COL3 = "REMAINING";
private static final String TAG = "Database Helper 1";
public DatabaseHelper1(#Nullable Context context) {
super(context, name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG , "Database 1 is being created");
String create_table = "CREATE TABLE "+name+"("+
COL0+" INTEGER, "+
COL1+" TEXT, "+
COL2+" DOUBLE, "+
COL3+" DOUBLE);";
db.execSQL(create_table);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+name);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private boolean createMonth(String month , String year){
Log.d(TAG , "month row is being created");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL0 , year);
contentValues.put(COL1 , month);
contentValues.put(COL2 , 0.0);
contentValues.put(COL3 , 0.0);
long result = db.insert(name,null , contentValues);
return result != -1;
}
public boolean spentChange(String month , String year , Double newAmount){
Log.d(TAG , "spent amount is being changed");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL2 , newAmount);
long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
return result != -1;
}
public boolean remainingChange(String month ,String year, Double newAmount){
Log.d(TAG , "Remaining amount is being changed");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues =new ContentValues();
contentValues.put(COL3 , newAmount);
long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
return result != -1;
}
public void checkExistance(String month, String year){
Log.d(TAG , "Checking if month already exits");
SQLiteDatabase database = this.getWritableDatabase();
Cursor cur = database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
System.out.println(cur);
if(cur.getCount() <= 0) {
boolean b = createMonth(month , year);
if(b)
Log.d(TAG , "checkExistance: failed to create month");
else
Log.d(TAG, "checkExistance: month created successfully");
}
}
public Cursor getdata(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM YEAR_DETAILS;";
return db.rawQuery(query , null);
}
public Cursor getSpentAmount(String month , String year){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
return db.rawQuery(query , null);
}
public Cursor getRemainingAmount(String month , String year){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
return cur;
}
}
AddTransaction class (where i am retrieving the data)
package com.carrot.wallet;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import com.carrot.wallet.ArrayListClasses.add_transaction_data;
import com.carrot.wallet.Database.DatabaseHelper1;
import com.carrot.wallet.Database.DatabaseHelper2;
import com.carrot.wallet.recyclerview.at_btn_adapter;
import java.util.ArrayList;
import java.util.Calendar;
import com.carrot.wallet.recyclerview.onClickRecyclerButtion;
public class AddTransaction extends AppCompatActivity {
int type1 ;
int type2;
double amount;
ArrayList<add_transaction_data> data;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_transaction);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
populateList();
final ImageButton cancel = findViewById(R.id.at_btn_cancel);
final EditText EditAmount = findViewById(R.id.at_enter_amount);
ImageButton save = findViewById(R.id.at_btn_save);
ImageButton income = findViewById(R.id.at_btn_income);
ImageButton loan = findViewById(R.id.at_btn_loan);
RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
#Override
public void onPositionClicked(int position) {
type1 = 2;
type2 = position;
}
}));
income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
type1 = 1;
type2 = -1;
}
});
loan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
type1 = 1;
type2 = -2;
}
});
context = this;
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("it is all cool here");
DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
double amount = Double.parseDouble(EditAmount.getText().toString());
System.out.println(amount);
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
String m = changeString(month);
System.out.println(type1);
String mRamount = "ds";
if(type1 == 1){
SQLiteDatabase database = databaseHelper1.getReadableDatabase();
String ca = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
Cursor cursor = database.rawQuery(ca , null);
mRamount = cursor.getString(1);
System.out.println(mRamount);//printing amount.
}
startActivity(new Intent(AddTransaction.this , MainActivity.class));
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AddTransaction.this , MainActivity.class));
}
});
}
void populateList(){
data = new ArrayList<>();
data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
}
String changeString(int month){
String m;
switch (month){
case 0:
m = "January";
break;
case 1:
m = "Feburary";
break;
case 2:
m = "March";
break;
case 3:
m = "April";
break;
case 4:
m = "May";
break;
case 5:
m = "June";
break;
case 6:
m = "July";
break;
case 7:
m = "August";
break;
case 8:
m = "September";
break;
case 9:
m = "October";
break;
case 10:
m = "November";
break;
case 11:
m = "December";
break;
default:
m = " ";
}
return m;
}
}
activity_main xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragNavHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation" />
<me.ibrahimsn.lib.SmoothBottomBar
android:elevation="30dp"
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
app:iconTint="#color/colorPrimary"
app:indicatorColor="#EFEFEF"
app:iconTintActive="#color/colorPrimaryDark"
app:textColor="#color/colorPrimaryDark"
android:layout_height="70dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_navigation_bar"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Can someone help me understand what is causing these two errrors.
in your getData() method you have double semicolon
String query = "SELECT * FROM YEAR_DETAILS;";
try changing it to
String query = "SELECT * FROM YEAR_DETAILS"
and I suggest you migrate to Room library

switch radiobox to checkbox to EditText using enum

I am creating a quiz with different question types. To call these types I would like to use Enum then a switch statement in my activity to make a specific type visible.
Here is what I have in my Question class
public class Question {
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private enum type {RADIO, CHECKBOX, TEXTENTRY};
public Question(){}
public Question(String question, String option1, String option2, String option3, int answerNumber, int type) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.type = type; // expression expected, not sure how to approach this
}
}
I manually created my getters + setters as I receive this message if I try to generate them with Android Studio
'no fields without getter + setter where found'
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
This is what I have in my DBHelper.
private void fillQuestionsTable() {
Question q1 = new Question("1 is correct", "a", "b","c",1,0);
addQuestion(q1);
Question q2 = new Question("2 is correct", "a", "b","c",2,1);
addQuestion(q2);
Question q3 = new Question("3 is correct", "a", "b","c",3,2);
addQuestion(q3);
}
private void addQuestion(Question question){
ContentValues cv = new ContentValues();
cv.put(QuestionsTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuestionsTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuestionsTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuestionsTable.COLUMN_OPTION3, question.getOption3());
cv.put(QuestionsTable.COLUMN_ANSWERNUMBER, question.getAnswerNumber());
cv.put(QuestionsTable.COLUMN_TYPE, question.getType());
db.insert(QuestionsTable.TABLE_NAME,null, cv);
}
public List<Question> getAllQuestions(){
List<Question> questionList = new ArrayList <>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME, null);
if (c.moveToFirst()){
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION3)));
question.setAnswerNumber(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWERNUMBER)));
question.setType(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_TYPE)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
return questionList;
}
And in my activity this is what I am using to try and switch the question types
-All views set to INVISIBLE to start then methods to make them VISIBLE-
private void showNextQuestion(){
if (questionCounter < getQuestionCounter){
currentQuestion = questionList.get(questionCounter);
question.setText(currentQuestion.getQuestion());
rb1.setText(currentQuestion.getOption1());
rb2.setText(currentQuestion.getOption2());
rb3.setText(currentQuestion.getOption3());
//switch question formats
int type = (int)
question.setText(currentQuestion.getQuestion()).questionList.get.questionType;
switch (questionType) {
// seems to like questionList better in here... still not sure how to bring up the enums
case Question.RADIO:
showRadioGroup();
break;
case Question.CHECKBOX:
showCheckboxes();
break;
case Question.TEXTENTRY:
showTypeAnswer();
break;
}
questionCounter++;
The idea is to bring everything from my Array - yes? -a bit confused here-
if I use questionList which is my array can't resolve
if I use getAllQuestions in case can't resolve getAllQuestions
if I use typeAnswer or questionList in case can't resolve RADIO nor TEXTENTRY
Sorry I was trying different approaches.
Also just realized I will have a hard time trying to verify a text entry with the code as is. Working on it.
Roughly speaking when you say private enum type {RADIO, CHECKBOX, TEXTENTRY}; you can (need to) then use type like as if it were a class.
So you need an additional line to declare an object of type for it to be a memeber ( enum ??? {...} is implicitly static and final (if my limited understanding is correct)) e.g. :-
private mytype = type;
Here's some code that may help you understand how to construct (in a few ways), get and set using enums :-
public class Question {
public enum qtype {RADIO,CHECKBOX,TEXTENTRY} //<<< accessible outside perhaps prefereable
private enum altqtype {RADIO, CHECKBOX, TEXTENTRY} //<<<< Alternative if you want private (restrictive)
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private long Id;
// Define members of the enum's
private qtype mytype;
private altqtype alternative_qtype;
private qtype another;
public Question(){}
public Question(
String question,
String option1,
String option2,
String option3,
int answerNumber,
int type, //<<<< pass as an int
String stype, //<<<< pass as a String
long id, //<<<< likely needed
qtype questiontype //<<<< pass as an qtype (e.g. qtype.RADIO)
) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.Id = id; //<<<< You may well need this to reference DB from Arraylist
// Setting enum's
this.mytype = questiontype; // set to passed value
this.alternative_qtype = altqtype.CHECKBOX; // Sets to default
// Set it accoring to the string passed
if (isValidTypeString(stype)) {
this.alternative_qtype = altqtype.valueOf(stype);
}
this.another = convertIntToQtype(type);
}
public qtype getMytype() {
return mytype;
}
public void setMytype(qtype mytype) {
this.mytype = mytype;
}
//Given an int convert it to a qtype
private qtype convertIntToQtype(int type){
qtype rv = qtype.TEXTENTRY;
switch (type) {
case 1:
rv = qtype.RADIO;
break;
case 2:
rv = qtype.CHECKBOX;
break;
case 4:
rv = qtype.TEXTENTRY;
break;
default:
rv = qtype.TEXTENTRY;
}
return rv;
}
// Check if a given string is valid as a question type
// Note done for alternative
private boolean isValidTypeString(String pv) {
boolean rv = false;
altqtype[] typearray = altqtype.values();
for (altqtype aqt: typearray) {
if (pv.equals(aqt.toString())) {
rv = true;
break;
}
}
return rv;
}
}
Working Example
here's a working example that :-
utilises enum's
utilises both ArrayList and Cursor
ArrayList used for asking question and for List of questions (2nd)
Cursor used for List of questions (1st List)
traverses questions via PREVIOUS and NEXT buttons
Allows answer (no answer checking) to be one of Edit text, Radio Button or Checkbox according to to the question, displaying the appropriate View.
Question.java
public class Question {
public enum qtype {RADIO,CHECKBOX,TEXTENTRY} //<<< accessible outside perhaps prefereable
private enum altqtype {RADIO, CHECKBOX, TEXTENTRY} //<<<< Alternative if you want private (restrictive)
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private long rowid;
// Define members of the enum's
private qtype mytype;
private altqtype alternative_qtype;
private qtype another;
public Question(){}
public Question(
String question, String option1, String option2, String option3,
int answerNumber, qtype type, long id) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.mytype = type;
this.rowid = id;
}
public Question(
String question, String option1, String option2, String option3,
int answerNumber, qtype type
){
this(question,option1,option2,option3,answerNumber,type,-1);
}
//<<<< Note constrcutor for demonstration of enums
public Question(
String question,
String option1,
String option2,
String option3,
int answerNumber,
int type, //<<<< pass as an int
String stype, //<<<< pass as a String
long id, //<<<< likely needed
qtype questiontype //<<<< pass as an qtype (e.g. qtype.RADIO)
) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.rowid = id; //<<<< You may well need this to reference DB from Arraylist
// Setting enum's
this.mytype = questiontype; // set to passed value
this.alternative_qtype = altqtype.CHECKBOX; // Sets to default
// Set it accoring to the string passed
if (isValidTypeString(stype)) {
this.alternative_qtype = altqtype.valueOf(stype);
}
this.another = convertIntToQtype(type);
}
public qtype getMytype() {
return mytype;
}
public void setMytype(qtype mytype) {
this.mytype = mytype;
}
//Given an int convert it to a qtype
private qtype convertIntToQtype(int type){
qtype rv = qtype.TEXTENTRY;
switch (type) {
case 1:
rv = qtype.RADIO;
break;
case 2:
rv = qtype.CHECKBOX;
break;
case 4:
rv = qtype.TEXTENTRY;
break;
default:
rv = qtype.TEXTENTRY;
}
return rv;
}
// Check if a given string is valid as a question type
// Note done for alternative
private static boolean isValidTypeString(String pv) {
boolean rv = false;
altqtype[] typearray = altqtype.values();
for (altqtype aqt: typearray) {
if (pv.equals(aqt.toString())) {
rv = true;
break;
}
}
return rv;
}
public static qtype convertStringToQtype(String s) {
qtype rv = qtype.TEXTENTRY; // <<<< Default
if (isValidTypeString(s)) {
rv = qtype.valueOf(s);
}
return rv;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
public String getOption3() {
return option3;
}
public void setOption3(String option3) {
this.option3 = option3;
}
public int getAnswerNumber() {
return answerNumber;
}
public void setAnswerNumber(int answerNumber) {
this.answerNumber = answerNumber;
}
public long getRowid() {
return rowid;
}
public void setRowid(long rowid) {
this.rowid = rowid;
}
}
QuestionsTable.java :-
public class QuestionsTable {
public static final String TABLE_NAME = "myquestions";
public static final String COLUMN_ID = BaseColumns._ID;
public static final String COLUMN_QUESTION = "question";
public static final String COLUMN_OPTION1 = "option1";
public static final String COLUMN_OPTION2 = "option2";
public static final String COLUMN_OPTION3 = "option3";
public static final String COLUMN_ANSWERNUMBER = "answernumber";
public static final String COLUMN_TYPE = "type";
}
DBHelper.java :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "questions.sqlite";
public static final int DBVERSION = 1;
SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crtsql = "CREATE TABLE IF NOT EXISTS " +
QuestionsTable.TABLE_NAME +
"(" +
QuestionsTable.COLUMN_ID + " INTEGER PRIMARY KEY," +
QuestionsTable.COLUMN_QUESTION + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION1 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION2 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION3 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_ANSWERNUMBER + " INTEGER NOT NULL," +
//<<<< NOTE will default to "TEXTENTRY"
QuestionsTable.COLUMN_TYPE + " TEXT NOT NULL DEFAULT '" +
Question.qtype.TEXTENTRY.toString() + "'" +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addQuestion(Question question){
ContentValues cv = new ContentValues();
cv.put(QuestionsTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuestionsTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuestionsTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuestionsTable.COLUMN_OPTION3, question.getOption3());
cv.put(QuestionsTable.COLUMN_ANSWERNUMBER, question.getAnswerNumber());
cv.put(QuestionsTable.COLUMN_TYPE, String.valueOf(question.getMytype()));
//<<<< alternative cv.put(QuestionsTable.COLUMN_TYPE,question.getMytype().toString());
db.insert(QuestionsTable.TABLE_NAME,null, cv);
}
public Cursor getQuestionsAsCursor() {
return db.query(QuestionsTable.TABLE_NAME,null,null,null,null,null,null);
}
public ArrayList<Question> getQuestionsAsArrayList() {
ArrayList<Question> rv = new ArrayList<>();
Cursor csr = db.query(QuestionsTable.TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(new Question(
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_QUESTION)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION1)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION2)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION3)),
csr.getInt(csr.getColumnIndex(QuestionsTable.COLUMN_ANSWERNUMBER)),
//<<< get the String and convert to qtype
Question.convertStringToQtype(
csr.getString(
csr.getColumnIndex(QuestionsTable.COLUMN_TYPE)
)
),
csr.getLong(csr.getColumnIndex(QuestionsTable.COLUMN_ID))
));
}
csr.close();
return rv;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="Hello World!"/>
<Button
android:id="#+id/prevquestion"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="wrap_content"
android:text="PREVIOUS"/>
<Button
android:id="#+id/nextquestion"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="wrap_content"
android:text="NEXT"/>
</LinearLayout>
<ListView
android:id="#+id/questionlist_by_cursor"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="41">
</ListView>
<ListView
android:id="#+id/questionlist_by_arraylist"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="41"
android:background="#FFDDDDFF">
</ListView>
<LinearLayout
android:orientation="horizontal"
android:id="#+id/questiondisplay"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="14">
<TextView
android:id="#+id/questiontext"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content" />
<RadioButton
android:id="#+id/answerrb"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:visibility="gone"/>
<CheckBox
android:id="#+id/answercb"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:visibility="gone"/>
<EditText
android:id="#+id/answeret"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mQuestionText;
Button mNext, mPrev;
RadioButton mRadio;
CheckBox mCheckBox;
EditText mTextEntry;
ListView mQuestionListByCursor,mQuestionListByArrayList;
DBHelper mDBHlpr;
Cursor mCsr;
SimpleCursorAdapter mSCA;
ArrayList<Question> mQuestionArrayList;
ArrayAdapter<Question> mArrayAdapter;
int mQuestionPointer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQuestionListByCursor = (ListView) this.findViewById(R.id.questionlist_by_cursor);
mQuestionListByArrayList = (ListView) this.findViewById(R.id.questionlist_by_arraylist);
mNext = (Button) this.findViewById(R.id.nextquestion);
mPrev = (Button) this.findViewById(R.id.prevquestion);
mRadio = (RadioButton) this.findViewById(R.id.answerrb);
mCheckBox = (CheckBox) this.findViewById(R.id.answercb);
mTextEntry = (EditText) this.findViewById(R.id.answeret);
mQuestionText = (TextView) this.findViewById(R.id.questiontext);
mDBHlpr = new DBHelper(this);
addSomeTestData(); //<<<< Add some test questions
mQuestionArrayList = mDBHlpr.getQuestionsAsArrayList(); //<<<< get the questions
refreshQuestion(); //<<<< Setup current (1st Question)
//Via Cursor
mCsr = mDBHlpr.getQuestionsAsCursor();
mSCA = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
mCsr,
new String[]{QuestionsTable.COLUMN_QUESTION,QuestionsTable.COLUMN_TYPE},new int[]{android.R.id.text1,android.R.id.text2},0);
mQuestionListByCursor.setAdapter(mSCA);
//Via ArrayList
mArrayAdapter = new ArrayAdapter<Question>(
this,
android.R.layout.simple_list_item_1,mQuestionArrayList
);
mQuestionListByArrayList.setAdapter(mArrayAdapter);
mPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mQuestionPointer > 0) {
mQuestionPointer--;
refreshQuestion();
}
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mQuestionPointer < (mQuestionArrayList.size() -1)) {
mQuestionPointer++;
refreshQuestion();
}
}
});
}
protected void onDestroy() {
super.onDestroy();
if (!mCsr.isClosed()) {
mCsr.close();
}
}
private void addSomeTestData() {
if (DatabaseUtils.queryNumEntries(
mDBHlpr.getWritableDatabase(),
QuestionsTable.TABLE_NAME
) < 1) {
mDBHlpr.addQuestion(new Question(
"What is 1 + 1?",
"0","1","2",
2,
Question.qtype.CHECKBOX //<<<< uses shorter signature
));
mDBHlpr.addQuestion(new Question(
"What is Tom's first name?",
"Fred","Tom","Bert",
1,
Question.qtype.TEXTENTRY //<<<< uses shorter signature
));
mDBHlpr.addQuestion(new Question(
"Where is Timbuktu?",
"Afirca","Russia","Australia",
1,
Question.qtype.RADIO //<<<< uses shorter signature
));
}
}
private void refreshQuestion() {
Question q = mQuestionArrayList.get(mQuestionPointer);
mQuestionText.setText(q.getQuestion());
switch (q.getMytype()) {
case TEXTENTRY:
mTextEntry.setVisibility(View.VISIBLE);
mRadio.setVisibility(View.GONE);
mCheckBox.setVisibility(View.GONE);
break;
case RADIO:
mRadio.setVisibility(View.VISIBLE);
mCheckBox.setVisibility(View.GONE);
mTextEntry.setVisibility(View.GONE);
break;
case CHECKBOX:
mCheckBox.setVisibility(View.VISIBLE);
mRadio.setVisibility(View.GONE);
mTextEntry.setVisibility(View.GONE);
break;
}
}
}
Screen Shots :-
When first started or restart :-
Notes
the List using a Cursor via SimpleCursorAdapter (1)
the List using an ArrayList<Question) (2)
Note the toString method hasn't been overridden hence the default toString method resulting in the funny values displayed.
the current (first) question, which as per the first list can be seen to be a checkbox question (3).
Next Question (question 2) after clicking the Next button :-
EditText i.e. TEXTENTRY question
Next Question (question 3 now)
This worked as well:
In
Question.java
enum QuestionType
{RADIO,CHECKBOX, TEXTENTRY}
public class Question {
...
private QuestionType type;
public Question(String question, String option1, String option2, String option3, int answerNumber,
QuestionType type) {
...
this.type = type;
}
//generate getters and setters using the generate tool in Android Studio
public QuestionType getType() {
return type;
}
public void setType(QuestionType type) {
this.type = type;
}
}
then in
QuizDnHelper.java
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionsTable.TABLE_NAME + " (" +
...
QuestionsTable.COLUMN_TYPE + " TEXT" + //not INTEGER!
")";
...
private void fillQuestionsTable(){
Question q1 = new Question("1 is correct", "a", "b","c",1,
QuestionType.RADIO);
private void addQuestion(Question question){
ContentValues cv = new ContentValues();
...
//set and get enum as string:
cv.put(QuestionsTable.COLUMN_TYPE, String.valueOf(question.getType()));
...
}
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME, null);
if (c.moveToFirst()){
do {
...
//set and get enum as string:
question.setType(QuestionType.valueOf(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_TYPE))));
...
} while (c.moveToNext());
And to call this into MainActivity:
QuestionType.RADIO
....
we use enums as a class.

Getting error in the on create method for sqlite database

I am creating a trivia game for a class assignment. I initially wanted to store the questions with categories in a sqlite database. I'm strating with one table, though I want to add others for category, level, and users, but first wanted to get it working with just questions. The program compiles and installs into the emulator and the first part works fine. It's not until the app goes to create the database that I get an error. The error reads:
Caused by:
android.database.sqlite.SQLiteException: near "TABLEquestion": syntax error (code 1): , while compiling: CREATE TABLEquestion(questionIDINTEGER PRIMARY KEY,questionNameTEXT,optionATEXT,optionBTEXT,optionCTEXT,answerTEXT,questionLevelIDINTEGER,categoryIDINTEGER)
at android.database.sqlite
My code for the main activity, trivia question activity, question class, DBHelper class and the xml layout for the Trivia Question activity. Please note, the error occurs when the radio button is selected for a category, which launches the Trivia Question activity. (before adding the database, the launch worked without error). Also, I know I need to create methods for Updating and Deleting records, but wanted to get the database creation working first. I've looked at this for 2 days and cannot find the issue. Any assistance would be greatly appreciated.
CLASS QUESTION:
public class Question {
private Integer questionID;
private String questionName;
private String optionA;
private String optionB;
private String optionC;
private String answer;
private Integer questionLevelID;
private Integer categoryID;
public Question(){
//// TODO: 11/5/2016
}
public Question (Integer questionID, String questionName, String optionA,
String optionB, String optionC, String answer, Integer questionLevelID,
Integer catID){
this.questionID=questionID;
this.questionName=questionName;
this.optionA=optionA;
this.optionB=optionB;
this.optionC=optionC;
this.answer=answer;
this.questionLevelID=questionLevelID;
this.categoryID = catID;
}
public void setqID(Integer questionId){
this.questionID = questionId;
}
public void setqName(String questionName){
this.questionName=questionName;
}
public void setqOptA(String optionA){
this.optionA = optionA;
}
public void setqOptB(String optionB){
this.optionB = optionB;
}
public void setqOptC(String optionC){
this.optionC=optionC;
}
public void setqAns(String answer){
this.answer = answer;
}
public void setQLevel(Integer questionLevelID){
this.questionLevelID = questionLevelID;
}
public void setqcatID(Integer categoryID){
this.categoryID= categoryID;
}
public int getqID(){
return questionID;
}
public String getqName(){
return questionName;
}
public String getqOptA(){
return optionA;
}
public String getqOptB(){
return optionB;
}
public String getqOptC(){
return optionC;
}
public String getqAns(){
return answer;
}
public Integer getqLevel(){
return questionLevelID;
}
public Integer getqCatID(){
return categoryID;
}
}
MAIN ACTIVITY:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.util.Log;
import java.util.List;
import static android.R.attr.id;
public class EduTriviaMain extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_trivia_main);
}
public String onCheckedChanged(View view) {
boolean checked = ((RadioButton) view).isChecked();
String category = "";
switch (view.getId()) {
case R.id.englishRadioButton:
if (checked) {
category = "english";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.historyRadioButton:
if (checked) {
category = "history";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.mathRadioButton:
if (checked) {
category = "math";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
default:
break;
}
return category;
}
}
DBHelper Class:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DBHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION=1;
//Database Name
private static final String DATABASE_NAME ="eduTrivia";
//table names
private static final String TABLE_QUESTION="question";
//question table column names
private static final String KEY_QUESTIONID = "questionID";
private static final String KEY_QUESTION="questionName";
private static final String KEY_OPTIONA="optionA";
private static final String KEY_OPTIONB="optionB";
private static final String KEY_OPTIONC="optionC";
private static final String KEY_ANSWER="answer";
private static final String KEY_LEVEL = "questionLevelID";
private static final String KEY_CATEGORYID="categoryID";
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE"
+ TABLE_QUESTION +"("
+ KEY_QUESTIONID +"INTEGER PRIMARY KEY,"
+ KEY_QUESTION + "TEXT,"
+ KEY_OPTIONA + "TEXT,"
+ KEY_OPTIONB + "TEXT,"
+ KEY_OPTIONC + "TEXT,"
+ KEY_ANSWER + "TEXT,"
+ KEY_LEVEL + "INTEGER,"
+ KEY_CATEGORYID + "INTEGER"+")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUESTION);
addQuestions();
}
private void addQuestions(){
Question q1 = new Question(1,"How do you write this number using words? 752",
"five hudnred sixty-two","seven hundred sixty-two", "seven hundred fifty-two",
"C",1,1);
Question q2 = new Question(2,"Round 5,764,438 to the nearest hundred thousand",
"6,200,000","5,800,000","5,700,000","B",1,1);
Question q3= new Question(3,"Which equation shows the associative property of addition",
"5+4=3+6","7+(4+3)=(7+4)+3", "0+8=8","B",1,1);
Question q4 = new Question(4,"Select the adjective in this sentence: Nina is a strong worker",
"Nina","strong","worker","B",1,2);
Question q5 = new Question (5,"Select the adjective in this sentence: The twon has three banks",
"The","town","three","C",1,2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists"+TABLE_QUESTION);
onCreate(db);
}
//constructor and getInstance() method
private static DBHandler mDBHANDLER;
public static synchronized DBHandler getInstance(Context context) {
if (mDBHANDLER==null){
mDBHANDLER=new DBHandler(context.getApplicationContext());
}
return mDBHANDLER;
}
public DBHandler(Context context){
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
public void addQuestion(Question question){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUESTIONID,question.getqID());
values.put(KEY_QUESTION,question.getqName());
values.put(KEY_OPTIONA,question.getqOptA());
values.put(KEY_OPTIONB,question.getqOptB());
values.put(KEY_OPTIONC,question.getqOptC());
values.put(KEY_ANSWER,question.getqAns());
values.put(KEY_LEVEL,question.getqLevel());
values.put(KEY_CATEGORYID,question.getqCatID());
db.insert(TABLE_QUESTION,null,values);
db.close();
}
//reading records
public Question getQuestion(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTION, new String[]{
KEY_QUESTIONID, KEY_QUESTION
},KEY_QUESTIONID + "=?",
new String[]{
String.valueOf(id)},null,null,null,null);
if (cursor !=null)
cursor.moveToFirst();
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2), cursor.getString(3),
cursor.getString(4),cursor.getString(5),Integer.parseInt(cursor.getString(6)),
Integer.parseInt(cursor.getString(7)));
return question;
}
public List<Question> getAllQuestions(){
//Select all questions query
List questionList = new ArrayList<Question>();
String selectAll = "SELECT * FROM "+TABLE_QUESTION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectAll,null);
//loop through all rows and add to the list
if (cursor.moveToFirst()){
do{
Question question = new Question ();
question.setqID(Integer.parseInt(cursor.getString(0)));
question.setqName(cursor.getString(1));
question.setqOptA(cursor.getString(2));
question.setqOptB(cursor.getString(3));
question.setqOptC(cursor.getString(4));
question.setqAns(cursor.getString(5));
//adding to list
questionList.add(question);
}while (cursor.moveToNext());
}
return questionList;
}
}
TRIVIA QUESTION ACTIVITY:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.List;
import static android.R.id.list;
public class TriviaQuestion extends AppCompatActivity {
List<Question> questionList;
int score=0;
int questionID = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda,rdb,rdc;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia_question);
DBHandler db = new DBHandler(this);
questionList = db.getAllQuestions();
currentQ = questionList.get(questionID);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
setQuestionView();
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getqName());
rda.setText(currentQ.getqOptA());
rdb.setText(currentQ.getqOptB());
rdc.setText(currentQ.getqOptC());
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getqAns().equals(answer.getText())) {
score++;
}
currentQ = questionList.get(questionID);
setQuestionView();
}
});
}
}
TRIVIA QUESTION LAYOUT XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_trivia_question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rasmussenandroid.sandra.edutrivia.TriviaQuestion">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
</RelativeLayout>
The error tells you what the issue is - the SQL query is not constructed properly. There should be spaces between the individual terms - for example, CREATE TABLEquestion should be CREATE TABLE question.
Try the following line for CREATE_TABLE_QUESTION :
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE "
+ TABLE_QUESTION +" ( "
+ KEY_QUESTIONID +" INTEGER PRIMARY KEY, "
+ KEY_QUESTION + " TEXT , "
+ KEY_OPTIONA + " TEXT, "
+ KEY_OPTIONB + " TEXT, "
+ KEY_OPTIONC + " TEXT, "
+ KEY_ANSWER + " TEXT, "
+ KEY_LEVEL + " INTEGER, "
+ KEY_CATEGORYID + " INTEGER "+")";

Display all data to listview using a tableview format

Below is my database that I have already created and it works fine, it can save the data to the database,I am really new to this android project and need guidance on how to display all data that was saved inside the listview.
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 BmiDatabase {
private data helper;
private SQLiteDatabase help;
private Context context;
public BmiDatabase(Context context){
helper = new data(context);
help = helper.getWritableDatabase();
this.context=context;
}
public long insertData(String bmi, String status, String weight){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(data.NAME, bmi);
contentValues.put(data._STATUS, status);
contentValues.put(data.WEIGHT, weight);
long id = db.insert(data.DATABASE_TABLE, null, contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {data.UID, data.NAME, data._STATUS, data.WEIGHT};
Cursor cursor = db.query(data.DATABASE_TABLE, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext())
{
// int index1 = cursor.getColumnIndex(data.UID);
// int cid = cursor.getInt(index1);
int cid = cursor.getInt(0);
String bmi = cursor.getString(1);
String status = cursor.getString(2);
String weight = cursor.getString(3);
buffer.append(cid +" "+bmi+" kg "+status+" "+weight+ "\n");
}
return buffer.toString();
}
public static class data extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME = "bmidatabase";
private static final String DATABASE_TABLE = "bmitable";
private static final int DB_VERSION = 7;
public static final String UID = "_id";
public static final String NAME = "Bmi";
public static final String _STATUS = "Status";
public static final String WEIGHT = "Weight";
private static final String DROP_TABLE= "DROP TABLE IF EXISTS "+DATABASE_TABLE;
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +
" "+NAME+" VARCHAR(255)," +
" "+_STATUS+" VARCHAR(255)," +
""+WEIGHT+" VARCHAR(255));";
public data(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
this.context=context;
}
public void getAllData(){
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Message.message(context,"Database Created");
}
catch (SQLException e){
Message.message(context, "Failed" +e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
Message.message(context, "DATABASE DELETED");
db.execSQL(DROP_TABLE);
onCreate(db);
}
catch(SQLException e){
Message.message(context, "SQL FAILED");
}
}
}
}
Below is the code for my mainactivity, it shows that I can display it using a toast, but I have no idea how to call the method to populate the list view with those data.
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static DataHelper DataHelper;
//DataHelper helper = new DataHelper(this);
private static BmiDatabase data;
private EditText weightinputid;
private EditText heightinputid;
private Button buttonBMI, save, detail;
private TextView BMIStatus;
private TextView BMIfinal;
private double weight =0.0;
private double height =0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupDB();
// setDB();
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
data = new BmiDatabase(this);
}
public void calculateBMI (View v){
String status;
weight= Double.parseDouble(weightinputid.getText().toString());
height= Double.parseDouble(heightinputid.getText().toString());
double bmi = weight/(height/100*height/100);
String result = String.format("%.2f", bmi);
Log.d("MainActivity", result);
BMIfinal.setText(result, TextView.BufferType.NORMAL);
if(bmi < 16){
status = "Seriously Underweight";
}
else if(bmi >=16.0 && bmi < 18.0){
status = "Underweight";
}
else if(bmi >=18.0 && bmi <24.0){
status = "Normal";
}
else{
status = "Obese";
}
BMIStatus.setText(status);
}
public void save(View v){
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String weight = weightinputid.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0)
{
Message.message(this, "");
}
else
{
Message.message(this, "");
}
}
public void detail(View v){
String d = data.getAllData();
Message.message(this, d);
}
}

Categories