Using variable created in private Oncreate() in public Intent - java

I cannot get the values of the four variables from the private Oncreate method to the public Intent method.
Below class creates a Pie Chart. Now i'm trying to fill this array with data from my SQlite database. int[] values = {dimensionPhysical, dimensionMental, dimensionSocial, dimensionSpirituality};
The database is openend in the oncreate method and I run 4 times the getcount query below.
public int getCount(String rowId) {
Cursor C = db.rawQuery("select count {*} from mainTable where " + KEY_DIMENSION + " = " + rowId, null);
return C.getCount();
}
Somehow I cannot get the values of the four variables from the private onCreate method to the public Intent method. The piechart is based on the intitial values of 1.
public class Balance extends Activity {
static DBAdapter myDb;
public int dimensionPhysical= 1;
public int dimensionMental= 1;
public int dimensionSocial= 1;
public int dimensionSpirituality= 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
openDB();
dimensionPhysical = myDb.getCount("Physical");
dimensionMental = myDb.getCount("Mental");
dimensionSocial = myDb.getCount("Social");
dimensionSpirituality = myDb.getCount("Spiritual");
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_ClearAll(View v) {
myDb.deleteAll();
}
public Intent getIntent(Context context) {
int[] values = {dimensionPhysical, dimensionMental, dimensionSocial, dimensionSpirituality};
CategorySeries series = new CategorySeries("Pie Graph");
int k = 0;
for (int value : values) {
series.add("Section " + ++k, value);
}
int[] colors = new int[]{Color.rgb(144, 238, 144), Color.rgb(173,216,230), Color.rgb(255,204,153), Color.rgb(240,204,153)};
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
renderer.setChartTitle("Pie Chart Demo");
renderer.setChartTitleTextSize(7);
renderer.setZoomButtonsVisible(true);
Intent intent = ChartFactory.getPieChartIntent(context, series, renderer, "Pie");
return intent;
}
}
I hope someone here knows how to fix this problem.

Try wrapping KEY_DIMENSION in single quotes (I guess it's a string):
Cursor C = db.rawQuery("select count {*} from mainTable where " + KEY_DIMENSION + " = '" + rowId + "'", null);
In any case, learn to use logcat and even debugger.

Related

how to add another column in another spinner of same or other table in android studio

how to add second column value of same or other table in another spinner from sqlite database using button click in android studio
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
});
Perhaps consider the following working example.
This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.
The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.
First the SQLite side i.e. the class that extends SQLiteOpenHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE1_TABLE = "_table1";
public static final String TABLE1_ID_COL = BaseColumns._ID;
public static final String TABLE1_NAME_COL = "_name";
public static final String TABLE1_DESC_COL = "_desc";
private static final String TABLE1_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE1_TABLE + "(" +
TABLE1_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE1_NAME_COL + " TEXT UNIQUE" +
"," + TABLE1_DESC_COL + " TEXT " +
");";
public static final String TABLE2_TABLE = "_table2";
public static final String TABLE2_ID_COL = BaseColumns._ID;
public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
public static final String TABLE2_NAME_COL = "_name";
private static final String TABLE2_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE2_TABLE + "(" +
TABLE2_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE2_TABLE1_ID_MAP_COL + " INTEGER " +
"," + TABLE2_NAME_COL + " TEXT" +
");";
public static final String TABLE3_TABLE = "_table3";
public static final String TABLE3_ID_COL = BaseColumns._ID;
public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
public static final String TABLE3_NAME_COL = "_name";
private static final String TABLE3_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE3_TABLE +"(" +
TABLE3_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE3_TABLE2_ID_MAP_COL + " INTEGER " +
"," + TABLE3_NAME_COL + " TEXT " +
");";
private static volatile DBHelper INSTANCE;
private SQLiteDatabase db;
public static final String SPINNER_COLUMN1 = "_spc1";
public static final String SPINNER_COLUMN2 = "_spc2";
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE1_CREATE_SQL);
db.execSQL(TABLE2_CREATE_SQL);
db.execSQL(TABLE3_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertTable1Row(String name,String description) {
ContentValues cv = new ContentValues();
cv.put(TABLE1_NAME_COL,name);
cv.put(TABLE1_DESC_COL,description);
return db.insert(TABLE1_TABLE,null,cv);
}
public long insertTable2Row(String name, long table1_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE2_NAME_COL,name);
cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
return db.insert(TABLE2_TABLE,null,cv);
}
public long insertTable3Row(String name, long table2_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE3_NAME_COL,name);
cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
return db.insert(TABLE3_TABLE,null,cv);
}
public Cursor getSpinnerData(String table, long map) {
String[] columns = new String[]{};
String whereClause = "";
String[] whereArgs = new String[]{String.valueOf(map)};
switch (table) {
case TABLE1_TABLE:
columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL + " AS " + SPINNER_COLUMN1,TABLE1_DESC_COL + " AS " + SPINNER_COLUMN2};
whereClause = "";
break;
case TABLE2_TABLE:
columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL + " AS " + SPINNER_COLUMN1,"'-' AS " + SPINNER_COLUMN2};
whereClause = TABLE2_TABLE1_ID_MAP_COL + "=?";
break;
case TABLE3_TABLE:
columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL + " AS " + SPINNER_COLUMN1,"'~' AS " + SPINNER_COLUMN2};
whereClause = TABLE3_TABLE2_ID_MAP_COL + "=?";
break;
}
if (map < 0) {
whereClause="";
whereArgs = new String[]{};
}
if (columns.length > 0) {
return db.query(table,columns,whereClause,whereArgs,null,null,null);
} else {
return db.query(TABLE1_TABLE,new String[]{"0 AS " + TABLE1_ID_COL + ",'ooops' AS " + SPINNER_COLUMN1,"'ooops' AS " + SPINNER_COLUMN2},null,null,null,null,null,"1");
}
}
}
as said there are three tables
a singleton approach has been utilised for the DBHelper
the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.
The Activity "MainActivity" used to demonstrate is :-
public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
Spinner sp1,sp2;
String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
SimpleCursorAdapter sca1,sca2;
String sp1_table_name = DBHelper.TABLE1_TABLE;
String sp2_table_name = DBHelper.TABLE2_TABLE;
Cursor csr1, csr2;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = this.findViewById(R.id.button1);
btn2 = this.findViewById(R.id.button2);
btn3 = this.findViewById(R.id.button3);
sp1 = this.findViewById(R.id.spinner1);
sp2 = this.findViewById(R.id.spinner2);
dbHelper = DBHelper.getInstance(this);
Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
if (test4Data.getCount() < 1) {
addSomeData();
}
test4Data.close();
sp1_table_name = DBHelper.TABLE1_TABLE;
sp2_table_name = DBHelper.TABLE2_TABLE;
setUpButtons();
setOrRefreshSpinner1();
setOrRefreshSpinner2();
}
void setUpButtons() {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE1_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE2_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE3_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
}
void setOrRefreshSpinner1() {
csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
if (sca1==null) {
sca1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr1,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp1.setAdapter(sca1);
} else {
sca1.swapCursor(csr1);
}
}
void setOrRefreshSpinner2() {
csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
if (sca2==null) {
sca2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr2,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp2.setAdapter(sca2);
} else {
sca2.swapCursor(csr2);
}
}
private void addSomeData() {
long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
long n3 = dbHelper.insertTable1Row("NAME003","The third name");
long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
}
}
Result
The above when run starts of with :-
With the first spinner dropdown shown :-
With the second spinner dropdown shown :-
If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-
If Button3 is clicked then data from Table3 is displayed in the second spinner:-
Clicking Button2 shows data from Table2.
Of course the principle could be applied in many different ways.
My adapters were not set so I made below changes and got expected result.
// RETRIEVE
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
sp1.setAdapter(adapter1);
sp2.setAdapter(adapter2);
});

android.database.sqlite.SQLiteException: near "WHERE": syntax error (Sqlite code 1)

I would be grateful if anyone could help with this code
android.database.sqlite.SQLiteException: near "WHERE": syntax error (Sqlite code 1): , while compiling: SELECT * FROM WHERE category = 'B', (OS error - 2:No such file or directory)
error from debug
My DbHelper is as following
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Quiz.db";
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private static final String KEY_OPTD= "optd"; //option d
private static final String KEY_CAT="category"; //category
private static final String TABLE_QUEST1 = "questUnit1";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase=db;
String sql1 = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST1 + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT, "+KEY_OPTD+" TEXT, "+KEY_CAT+" TEXT)";
db.execSQL(sql1);
addQuestionsUnit1();
}
private void addQuestionsUnit1() {
QuestionUnit1 q101 = new QuestionUnit1("What is the decimal equivalent of the binary number 10111","21","23","39","42","23","B");
this.addQuestionsUnit1(q101);
QuestionUnit1 q102 = new QuestionUnit1("In order to write on a floppy disk with your IBM PC, you must first","digitize it","format it","compile it","hardware it","format it","B");
this.addQuestionsUnit1(q102);
QuestionUnit1 q249= new QuestionUnit1("Firewalls are used to protect against","Unauthorized Attacks","Viruses","Fire Attacks","Data Driven Attacks","Unauthorized Attacks","E");
this.addQuestionsUnit1(q249);
QuestionUnit1 q250= new QuestionUnit1("The first Digital Computer introduced, was named as ","UNIVAC","EDSAC","ENIAC","MARK-1","MARK-1","E");
this.addQuestionsUnit1(q250);
}
public void addQuestionsUnit1(QuestionUnit1 quest) {
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
return quesList1;
}// end pubic list
}
the code walks like that a butto to To Exercise Activity
if(position == 2){
Intent i= new Intent(getApplicationContext(),Unit1ExerciseActivity.class);
i.putExtra("table_name",tableName);
i.putExtra("level_name","B");
startActivity(i);
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
and the code in the exercise Activity is
public class Unit1ExerciseActivity extends AppCompatActivity {
List<QuestionUnit1> quesList1;
public int score=0;
int ctr1=1;
QuestionUnit1 currentQ1;
TextView txtQuestion1;
RadioGroup grp;
RadioButton rda1, rdb1, rdc1, rdd1;
Button butNext1;
Random random1 = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
TextView textViewTime1;
public ArrayList<String> wrongQuestListUnit1 = new ArrayList<String>();
public ArrayList<String> selectedAnsUnit1 = new ArrayList<String>();
public ArrayList<String> actualAnswerUnit1 = new ArrayList<String>();
int number;
ProgressBar progressBar;
int progress = 1;
String tableName="",catName="";
TextView qstnNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unit1_exercise_activity);
qstnNo = (TextView)findViewById(R.id.qstnNo);
Intent iin=getIntent();
Bundle b=iin.getExtras();
if(b!=null){
tableName=(String)b.get("table_name");
catName=(String)b.get("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
number=0;
DbHelper db= new DbHelper(this);
textViewTime1 = (TextView)findViewById(R.id.textViewTime);
final CounterClass timer = new CounterClass(1800000, 1000);
timer.start();
quesList1=db.getAllQuestions1(tableName,catName);
for(int i=0;i<50;i++){
while(true){
int next = random1.nextInt(50);
if(!list.contains(next))
{
list.add(next);
break;
}
}
}
currentQ1=quesList1.get(list.get(0));
txtQuestion1=(TextView)findViewById(R.id.textView1);
rda1=(RadioButton)findViewById(R.id.radio0);
rdb1=(RadioButton)findViewById(R.id.radio1);
rdc1=(RadioButton)findViewById(R.id.radio2);
rdd1=(RadioButton)findViewById(R.id.radio3);
butNext1=(Button)findViewById(R.id.button1);
setQuestionView();
grp = (RadioGroup) findViewById(R.id.radioGroup1);
butNext1.setEnabled(false);
grp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i== R.id.radio0 || i == R.id.radio1 || i==R.id.radio2 || i == R.id.radio3)
butNext1.setEnabled(true);
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(30);
progressBar.setProgress(1);
butNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress = progress+1;
progressBar.setProgress(progress);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
//Log.d("yourans", currentQ1.getANSWER1() + " " + answer.getText());
if (currentQ1.getANSWER1().equals(answer.getText())) {
score++;
//Log.d("score", "Your score" + score1);
}
else
{
wrongQuestListUnit1.add(number, currentQ1.getQUESTION1());
selectedAnsUnit1.add(number, answer.getText().toString());
actualAnswerUnit1.add(number, currentQ1.getANSWER1());
number++;
}
grp.clearCheck();
butNext1.setEnabled(false);
if (ctr1 < 31) {
if (ctr1 == 30) {
butNext1.setText("End Test");
}
currentQ1 = quesList1.get(list.get(ctr1));
setQuestionView();
} else {
timer.onFinish();
timer.cancel();
}
}
});
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
textViewTime1.setText(hms);
}
#Override
public void onFinish() {
showResult();
}
}
public void showResult(){
Intent intent = new Intent(Unit1ExerciseActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("scoreUnit1 ", score);//Your score
b.putString("section",tableName);//Your table name
b.putString("category",catName);//Your category name
intent.putStringArrayListExtra("wrongQuestions", wrongQuestListUnit1);
intent.putStringArrayListExtra("selectedAnswer", selectedAnsUnit1);
intent.putStringArrayListExtra("actualAnswer", actualAnswerUnit1);
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
private void setQuestionView(){
txtQuestion1.setText(currentQ1.getQUESTION1());
rda1.setText(currentQ1.getOPTA1());
rdb1.setText(currentQ1.getOPTB1());
rdc1.setText(currentQ1.getOPTC1());
rdd1.setText(currentQ1.getOPTD1());
if(ctr1<10)
qstnNo.setText("0" + ctr1 + "/30");
else
qstnNo.setText("" + ctr1+ "/30");
ctr1++;
}
#Override
public void onBackPressed() {
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("If you close all your progress would not be saved... Do you wish to exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
// alert.setTitle("CompQuiz");
alert.show();
}
}
You are probably passing/getting a null tableName.
Try this:
if(b!=null){
tableName=b.getString("table_name");
catName=b.getString("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
Try this please:
public void addQuestionsUnit1(QuestionUnit1 quest){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("DB insertion", "Error while trying to add values to database");
} finally {
db.endTransaction();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase= getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
cursor.close();
return quesList1;
}
}

Sum two numbers in SQL database

I have a program to sum two numbers and save result in SQL then show results in a TextView but I don't know how to make that; help me please.
But this number comes from the user (EditText) or from button ...
must I make a new table for the sum number for example or what .
I watch videos on you tube but I can do it that program.
this my code...
in DataBase activity :
public class DB_sql extends SQLiteOpenHelper {
public static final String name = "data.db";
public static final String TABLE_NAME="mydata";
public static final String KEY_First="first";
public static final String KEY_second="second";
public DB_sql(#Nullable Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table TABLE_NAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, KEY_First INTEGER, KEY_second INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
public boolean insertdata (int first,int second){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues numbers = new ContentValues();
numbers.put("first",first);
numbers.put("second",second);
long result = db.insert(TABLE_NAME,null,numbers);
if (result == -1)
return false;
else
return true;
}
in result activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView)findViewById(R.id.result);
int first = getIntent().getIntExtra("number1",0);
int second = getIntent().getIntExtra("number2",0);
Boolean dataSQL = db_sql.insertdata(first,second);
if (dataSQL == true){
Toast.makeText(this,"data inserted",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"data not inserted",Toast.LENGTH_SHORT).show();
}
in MainActivity:
public class MainActivity extends AppCompatActivity {
// DB_sql db_sql = new DB_sql(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void second(View view) {
Intent sec = new Intent(this,result.class);
sec.putExtra("number2",40);
startActivity(sec);
}
public void first(View view) {
Intent fir=new Intent(this,result.class);
fir.putExtra("number1",85);
startActivity(fir);
}
}

Android Studio: app not saving to/reading from database

So my app is a QR Code scanner. Currently it will read a QR code and display it back to user. I want to get it to also save this result to a database and then proceed to read back from it. Currently it does neither of the last two and I'm struggling to figure out which is causing the issue - either saving to the database or reading back from the database.
My Database code is this:
public class Database {
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"codeid INTEGER PRIMARY KEY AUTOINCREMENT, " +
"code TEXT NOT NULL);";
public Database(Context ctx) {
this.dbContext = ctx;
}
public Database open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put("codes", code);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public ArrayList<String[]> fetchUser(String code) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"codeid", "code",
}, "code LIKE '%" + code + "%'", null,
null, null, null);
int codeNameColumn = mCursor.getColumnIndex("code");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(codeNameColumn);
pointer++;
} while (mCursor.moveToNext());
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "codeid", "codes" }, null, null, null, null, "codeid");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0);
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
And my main java code is this.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button Scan;
private ArrayList<String[]> viewall;
private TextView QR_output;
private IntentIntegrator ScanCode;
private ListView lv;
private ArrayList Search = new ArrayList();
ArrayList<String[]> searchResult;
Database dbh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this caused an error on earlier APKs which made the app switch from 17 to 27
setContentView(R.layout.activity_main);
// Defines the Scan button
Scan = findViewById(R.id.Scan);
// defines the output for text
QR_output = findViewById(R.id.QR_Output);
// looks for the user clicking "Scan"
Scan.setOnClickListener(this);
ScanCode = new IntentIntegrator(this);
// Means the scan button will actually do something
Scan.setOnClickListener(this);
lv = findViewById(R.id.list);
dbh = new Database(this);
dbh.open();
}
public void displayAll(View v){
Search.clear();
viewall = dbh.selectAll();
String surname = "", forename = "";
for (int count = 0 ; count < viewall.size() ; count++) {
code = viewall.get(count)[1];
Search.add(surname + ", " + forename);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
Search);
lv.setAdapter(arrayAdapter);
}
// will scan the qr code and reveal its secrets
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
// if an empty QR code gets scanned it returns a message to the user
if (result.getContents() == null) {
Toast.makeText(this, "This QR code is empty.", Toast.LENGTH_LONG).show();
} else try {
// converts the data so it can be displayed
JSONObject obj = new JSONObject(result.getContents());
// this line is busted and does nothing
QR_output.setText(obj.getString("result"));
} catch (JSONException e) {
e.printStackTrace();
String codes = result.getContents();
boolean success = false;
success = dbh.createUser(codes);
// outputs the data to a toast
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onClick(View view) {
// causes the magic to happen (It initiates the scan)
ScanCode.initiateScan();
}
}
Your issue could well be with the line initialValues.put("codes", code); as according to your table definition there is no column called codes, rather the column name appears to be code
As such using initialValues.put("code", code); may well resolve the issue.
Addititional
It is strongly recommended that you define and subsequently use constants throughout your code for all named
items (tables, columns, views trigger etc) and thus the value will always be identical.
e.g.
private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
public static final String COLUMN_CODEID = "codeid"; //<<<<<<<<< example note making public allows the variable to be used elsewhere
public static final String COLUMN_CODE = "code"; //<<<<<<<<<< another example
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_CODEID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //<<<<<<<<<<
COLUMN_CODE + " TEXT NOT NULL);"; //<<<<<<<<<<
........ other code omitted for brevity
public boolean createUser(String code) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_CODE, code); //<<<<<<<<<< CONSTANT USED
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
You would also likely encounter fewer issues by not using hard coded column offsets when extracting data from Cursor by rather using the Cursor getColumnIndex method to provide the offset.
e.g. instead of :-
results.get(counter)[0] = cursor.getString(0);
it would be better to use :-
results.get(counter)[0] = cursor.getString(cursor.getColumnIndex(COLUMN_CODEID));

Desperate Answer Needed:Android Sqlite Table is not creating

Community I m new in android so to just implement the concept of sqlity from udacity as guided,I built a small app...as show below code with category activity(main) EVEN I CALLED getReadeableDatabase() on open helper class in onCreate of main activity(catalog),clear data,uninstalled app,no solution found?
public class CatalogActivity extends AppCompatActivity {
sqlitedbhelper sqdb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Setup FAB to open EditorActivity
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
sqdb = new sqlitedbhelper(this);
Log.v("my tag", "0");
displaydata();
}
public void displaydata() {
SQLiteDatabase mdb = sqdb.getReadableDatabase();
String[] projection = {
PetContract.petdata.col_id,
PetContract.petdata.col_name,
PetContract.petdata.col_breed,
PetContract.petdata.col_sex,
PetContract.petdata.col_weight};
// Perform a query on the pets table
Cursor cursor = mdb.query(
PetContract.petdata.pet_table, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null); // The sort order
TextView txt = (TextView) findViewById(R.id.text_view_pet);
try {
txt.setText("no of columns:");
txt.append(String.valueOf(cursor.getCount()));
} finally {
cursor.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Insert dummy data" menu option
case R.id.action_insert_dummy_data:
// Do nothing for now
return true;
// Respond to a click on the "Delete all entries" menu option
case R.id.action_delete_all_entries:
// Do nothing for now
return true;
}
return super.onOptionsItemSelected(item);
}
}
Below is the contract class
public final class PetContract {
private PetContract() {}
public static final class petdata implements BaseColumns{
public static final String pet_table="pet";
public static final String col_name="name";
public static final String col_weight="weight";
public static final String col_breed="breed";
public static final String col_id=BaseColumns._ID;
public static final String col_sex="sex";
//constants starts here
public static final int sex_male=1;
public static final int sex_female=2;
public static final int sex_unknown=0;
}
}
And finally the sqlitedbhelper class
public class sqlitedbhelper extends SQLiteOpenHelper {
public static final int database_ver=1;
public static final String database_nAME="shelter";
public sqlitedbhelper(Context context) {
super(context, database_nAME, null, database_ver);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.v("my tag","in on create db helper");
String SQL_CREATE_PETS_TABLE = "CREATE TABLE " + petdata.pet_table + " ("
+ petdata.col_id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ petdata.col_name + " TEXT NOT NULL, "
+ petdata.col_breed + " TEXT, "
+ petdata.col_sex + " INTEGER NOT NULL, "
+ petdata.col_weight + " INTEGER NOT NULL DEFAULT 0);";
Log.v("my tag"," b4 passed sql create db helper");
db.execSQL(SQL_CREATE_PETS_TABLE);
Log.v("my tag","passed sql create db helper");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Now the problem is when I run it database named shelter is created but no table is created.
You have to mention this at your CatalogActivity inside onCreat method
sqdb = new sqlitedbhelper (this);
This will help you..

Categories