SQLite- button adds value to db.query - android

I've got a database with the following columns:
Book_name, book_id, chapter_number, chapter_id, line_number, line_id
I'm doing this app to read books, select a chapter to read, and then display all the lines.
First listview displays all the books, when the user selects on a book name, it passes the book_id to display all the chapters under that book, when selecting a chapter, it passes the chapter_id to display all the lines under that chapter.
My question is, when a user is busy reading they must press the back button to display all the chapters again and then select the next chapter. I want to put a button on the listview displaying all the lines (after the chapter has been selected) for the user to press and then it should basically re-query the db to display the next available chapter.
Each listview is in it's own activity and id's gets passed with Intents.
I don't know what code you guys want to see so please just ask.
This is the list in DBHandler2 for the chapters:
public List<defineBybeldbAlles> getListHoofstuk(String boek_id_na_hoofstuk){
defineBybeldbAlles defineBybeldbHoofstuk = null;
List<defineBybeldbAlles> defineBybeldbAllesList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_BOEK_ID + " = '" + boek_id_na_hoofstuk + "'GROUP BY hoofstuk_id ORDER BY hoofstuk_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbHoofstuk = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7),cursor.getInt(8),cursor.getString(9),cursor.getString(10));
defineBybeldbAllesList.add(defineBybeldbHoofstuk);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbAllesList;
}
This is where I pass the chapter_id in my chapter activity to diplay the lines in the lines activity:
public void onItemClick (AdapterView<?> arg0, View view, int arg2, long arg3){
//on selecting a hoofstk
//BybelActivityVers will be launched to show verse inside
Intent hoofstukIntent = new Intent(BybelActivityHoofstuk.this,BybelActivityVers.class);
//send hoofstuk_id to VersActivity to get verse under that book
String hoofstuk_id_na_vers = ((TextView)view.findViewById(R.id.hoofstuk_id)).getText().toString();
hoofstukIntent.putExtra("hoofstuk_id", hoofstuk_id_na_vers);
String hoofstuk_nommer_na_vers = ((TextView)view.findViewById(R.id.custom_row_hoofstuktext)).getText().toString();
hoofstukIntent.putExtra("custom_row_hoofstuktext", hoofstuk_nommer_na_vers);
startActivity(hoofstukIntent);
}
});
Now this is the list in DBHandler3 for the lines:
public List<defineBybeldbAlles> getListVers(String hoofstuk_id_na_vers){
defineBybeldbAlles defineBybeldbVers = null;
List<defineBybeldbAlles> defineBybeldbVersList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_HOOFSTUK_ID + " = '" + hoofstuk_id_na_vers + "'GROUP BY vers_id ORDER BY vers_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbVers = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7),cursor.getInt(8),cursor.getString(9),cursor.getString(10));
defineBybeldbVersList.add(defineBybeldbVers);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbVersList;
}

Set variable chapterid + 1 in current chapter to be passed in intent
Then Intent i = new intent(PARAMETERS);
finish();
startactivity(i);
Then run the query with db to get details of new chapter in new intent
Its working thanks

In your ques add a button .
check if list is scrolled to last
'
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mListView.getAdapter() == null)
return ;
if (mListView.getAdapter().getCount() == 0)
return ;
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !isLoading) {
// It is time to add new data. We call the listener
isLoading = true;
}
}
});
'
when is loading is true dat means ur list is at its last
and then make nextbutton.setvisibility(View.Visible);
and on click of button
get ur chapter id and add 1 to it i.e.. next chapter id
and start intent and pass chapter and page id with dat intent like
Intent i = new Intent(this,Currentclass.java);
finish();
start activity(i);
// your page will be changed now
please tick the answer as correct thanks:)

Related

next button for listview

My first activity contains a ListView that's getting a list of items from a database.
And in the OnClickListener, there is a new activity that's open getting all information related to the question from the database, I'm putting them in Intent extras and getting them in the next activity:
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_CIBLE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLANACT));
int ID = cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION);
inte.putExtra("question", quest);
inte.putExtra("repo", repA);
inte.putExtra("cible", cible);
inte.putExtra("plan", plan);
// inte.putExtra("id", ID);
// inte.putExtra("pos", pos);
startActivity(inte);
finish();
In the info activity, it's simple and I could get the information from the database, here's the code
Intent intent = getIntent();
String question = intent.getStringExtra("question");
String repo = intent.getStringExtra("repo");
String cible = intent.getStringExtra("cible");
String plan = intent.getStringExtra("plan");
final int[] ID = {0};
ID[0] = intent.getIntExtra("ID", ID[0]);
int pos = 0;
pos = intent.getIntExtra("pos",pos);
txtq.setText(question);
txtr.setText(repo);
txtc.setText(cible);
txtp.setText(plan);
I want to add a button NEXT that makes appear the next item in the list by refreshing the same page without going back to the list and click again.
I tried to get the position too with the intent and tried to set a new OnClickListener in the button to set the position = position +1, but it doesn't work.
Any ideas?
First solution
for that, you have to pass the entire list to next activity so you can directly do next item in the list by refreshing the same page without going back.
Second solution.
You have to separately apply query for next info page click on the next/previous button.
You just need to go through the sql Queries
select * from table where key=primaryKey limit Page_Limit offset Start_From
You need to change limit and offset on select of list limit.

Let user add/remove favorites from drawer/listview from position and save it to SQLite db

I have a sqlite database prepopulated with some data and I would like to have method/function that enables the user to "save" the info in his favorites and display it. The only problem is i have problems with the queries to work properly. I don't understand how to get the position from the current displayed data (from the db) in the activity and save it to the database. I have a column called "Favorites" in db with the default value set to "no" and when the user click a button the value should change to "yes".
The user click a row in listview populated from the DB and it starts a new activity with intent.putExtra(data from db). The new activity displays the data in a single textview. In this new activity i've made a navigation drawer/listview(shows by sliding or "hamburger meny"). In this nav drawer I have a "button" that i would like to get the id from the db according to the current displayed data and change the value of the column "Favorite". In a another class i used
Cursor c = dbHelper.showBook(Integer.toString(position + 1));
Got this help from another recent thread of mine and it worked fine but my new problem is that i have if statements as below. The start of intent works fine. But I want to call a method from my dbHelper to update rows in db. And the code above dont work(but no errors) when i try to use it. The toast shows but nothing is happening in the DB.
myDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Intent iHome = new Intent(DisplayBook.this, MyAccont.class);
startActivity(iHome);
else if (position == 3){
dbHelper.addFavorites(Integer.toString(position+ 1));
Toast.makeText(getApplicationContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
the dbHelper.addFavorites: (the addFavs param is supposed to be the id/pos of the db row as in the working code above)
public void addFavorites(String addFavs){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FAV, "yes");
String whereClause = COL_ID + " = ?" ;
String[] whereArgs = new String[] { addFavs};
db.update(
TABLE_NAME,
values,
whereClause,
whereArgs);
}
I've tried a fair amount of versions och different codes and stuff but nothing works and now I'm asking for som advice on this. How can i do it in a good an efficient way? Thank you so much for any help at all!
EDIT: Solved it by using arrays instead of stringbuilder. I save the id from the database in [0] and used it in dbHelper.addFavorites(myStringArray[0]);
and in
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = dbHelper.aClass(Integer.toString(position + 1));
StringBuilder sb = new StringBuilder();
while (c.moveToNext()) {
myStringArray[0] = c.getString(0);
myStringArray[1] = c.getString(4);
Intent i = new Intent(classA.this, classB.class);
i.putExtra(null, myStringArray);
startActivity(i);
I'm not shure, but your problem may be this line
ContentValues values = new ContentValues();
try to change it to:
ContentValues values = new ContentValues(1);
From my experience u should write amount of variables u want to send to your db.

Accessing cursor while iterating through another cursor fails to deliver data in time

I have a database with foods that are displayed in a tablelayout with up to 20 lines of foods. The foods may have different measurement units that are retrieved through a union select query among three tables, and displayed in a spinner for each food in the table. When the user selects a unit of measurement in the spinner, the cursor is moved to the appropriate position so as to get the nutrients for the food's selected unit of measurement (through spinner's onItemSelected Listener).
Well the problem is when I select a food record from a listview in order to update it in the food insertion display, when I try to recreate the food record iterating through the different foods in the record. When the food cursor is in a food row it calls the method that loads the different units of measurement for that particular food, and also selects the record's unit of measurement for that food, which I remind you, on selecting the unit the unitsCursor moves to the appropriate column to get the nutrients for that unit.
Unfortunately the unitsCursor misses to deliver the data in time and the food row is partially filled when the foodCursor moves to the next lines. I cannot figure out why this is happening. Below is the method that loads the units spinner with the units of measurement and some code from the method that recreates the food record in the food insertion screen
protected void fillUnitsSpinner(String food) {
unitsCursor = mDataBaseHelper.getFoodMatches(food, null, CURSOR_FOR_UNITS_SPINNER);
foodUnits.clear();
if(unitsCursor != null) {
unitsCursor.moveToFirst();
while(!unitsCursor.isAfterLast()) {
// Get unit string
String unit = unitsCursor.getString(unitsCursor.getColumnIndex(FoodDBHelper.UNITS));
// Get practical units' extra columns if present
String fingerTip = unitsCursor.getString(unitsCursor.getColumnIndex(
FoodDBHelper.FINGERTIP));
// If practical units are present
if(fingerTip != null) {
foodUnits.add(FINGERTIP.getpUnit());
foodUnits.add(FINGER.getpUnit());
foodUnits.add(HAND.getpUnit());
foodUnits.add(FIST.getpUnit());
foodUnits.add(CUP.getpUnit());
}
else foodUnits.add(unit);
unitsCursor.moveToNext();
}
unitsCursor.moveToFirst();
ArrayAdapter<CharSequence> unitsAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.food_act_units_spinner_dropdown_item);
unitsAdapter.addAll(foodUnits); // load adapter with food units
unitsAdapter.setDropDownViewResource(R.layout.food_act_units_spinner_dropdown_item);
mUnitsSpinner.setAdapter(unitsAdapter); // set adapter
Log.i(TAG, "spinnerItem = " + unitsAdapter.getItem(foodUnits.indexOf(foodUnits.get(0))));
// Select and set unit from the main table to the spinner
if(!editRecord)
mUnitsSpinner.setSelection(unitsAdapter.getPosition(foodUnits.get(0)));
mUnitsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "pos = " + pos);
TextView unitsText = (TextView) view.findViewById(R.id.f_a_units_item);
int pUnitsPos = -1;
String pShortcutUnit;
switch(pos) {
case MAIN_TABLE:
unitsCursor.moveToPosition(MAIN_TABLE);
break;
// other cases
String unitsChoice = unitsText.getText().toString();
assigned = getValuesFromCursor(unitsCursor, unitsChoice);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
}
and...
// Fill foodTable with records
if(c != null && c.moveToFirst()) {
Log.i(TAG, "c.getCount = " + c.getCount());
while(!c.isAfterLast() && makeRow(c)) {
c.moveToNext();
}
}
setListenersToFoodRows();
foodTable.requestLayout();
In the makeRow(Cursor c) method there is a call to fillUnitsSpinner(foodName);
I finally solved it. The problem was that I used a class variable as unitsCursor, while the correct was to use an instance variable.

Get value from spinner and change Text View depending on that value

Ok this should be straight forward but i'm having difficulty with it. So far i've got this code.
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
SpinnerFAQ = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + SpinnerFAQ,
Toast.LENGTH_LONG).show();
TextView tv = (TextView) findViewById(R.id.faq_answer);
ExerciseData question = new ExerciseData(this);
question.open();
String answer = question.getFaqAnswer();
question.close();
tv.setText(answer);
}
SpinnerFAQ is a global variable and it stores the value of the spinner as String.
public String getFaqAnswer() {
// TODO Auto-generated method stub
String[] columns = new String[] { FAQ_ROWID, FAQ_QUESTION, FAQ_ANSWER};
Cursor c = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(FAQ_ROWID);
int iQuestion = c.getColumnIndex(FAQ_QUESTION);
int iAnswer = c.getColumnIndex(FAQ_ANSWER);
//c.getString(iRow) + " " +
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
{
result = result + c.getString(iAnswer) + "\n";
break;
}
}
return result;
}
This is based on code I've already used, but basically I want to check the Spinner against the Question in my Database and if they match I want to change the Text View to the answer. Right now the FAQ.SpinnerFAQ works fine, but c.getString(iQuestion) always shows up as the last value in the database. This code "result = result + c.getString(iAnswer) + "\n";" works fine without the if statement, so I don't really understand why there is a problem with "c.getString(iQuestion)". Any help would be greatly appreciated.
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
Never compare Strings with == in Java, always use equals(). Please read: How do I compare strings in Java? and change every String comparison to:
if(FAQ.SpinnerFAQ.equals(c.getString(iQuestion)))

android sqlite next record incorrect

This is the getContact method which takes the rowID in this case the counter
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
question, possibleAnsOne,possibleAnsTwo, possibleAnsThree,realQuestion,userR}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
// moves to the the first record
mCursor.moveToFirst();
}
return mCursor;
}
Here is my problem. I start at record one. So the counter is set to one.
in the public oncreate method. When I click next for some reason it is not setting the value of the first record with db.updateUserResult(counter,8); I think it is missing the first record. The reason I know this is that if I chose the answer which is one ahead. Lets say that Question 1 right answer is option 2 and Question 2's right answer is option 3. If you choose option 3 for question 1 then you get the right answer. If i keep choosing the right answer one record ahead I get all the right results.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
boolean TimerStarted = b.getBoolean("timerlogic");
System.out.println("what is the logic of the timer" + TimerStarted);
Log.e(LOGS, "Whatis the first value for the timer inside the timer_btn" + TimerStarted);
setContentView(R.layout.basic);
// this method is better then a try and catch block as it actually prevents the occurence occuring instead of just patching it.
// the purpose of t
db.open();
Cursor c = db.getContact(1);
if(c.isFirst())
{
TextView question = (TextView)findViewById(R.id.question);
RadioButton radio1 = (RadioButton)findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton)findViewById(R.id.radio2);
RadioButton radio3 = (RadioButton)findViewById(R.id.radio3);
answerCounterText = (TextView)findViewById(R.id.answerCounterText);
answerCounterText.setText(String.valueOf("0"));
// for the first record set the counter to zero
// question.setText(String.valueOf("0"));
TextView QuestionNumber = (TextView)findViewById(R.id.QuestionNumber);
Complete = (Button)findViewById(R.id.Continue);
Complete.setBackgroundResource(R.drawable.complete);
Complete.setVisibility(View.INVISIBLE);
QuestionNumber.setText(String.valueOf("Question Number :" + counter));
System.out.println("what is the setup counter after loop" + counter);
//DisplayContact(c,radio1);
DisplayRadioButton(c,radio1,radio2,radio3,question);
}
// }
// }
// Previous = (Button)findViewById(R.id.Previous);
Next = (Button)findViewById(R.id.Next);
Next.setBackgroundResource(R.drawable.next);
// get the results from the checked box
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Cursor c = db.getContact(1);
/*
if (firstrecordchosen)
{
Cursor c = db.getContact(1);
System.out.println("what is the current value of the counter 0" + counter);
firstrecordchosen = false;
}
counter++;
*/
counter++;
Cursor c = db.getContact(counter);
if (c.moveToFirst() && !c.isNull(0))
{
TextView question = (TextView)findViewById(R.id.question);
RadioButton radio1 = (RadioButton)findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton)findViewById(R.id.radio2);
RadioButton radio3 = (RadioButton)findViewById(R.id.radio3);
TextView answerCounterText = (TextView)findViewById(R.id.answerCounterText);
TextView QuestionNumber = (TextView)findViewById(R.id.QuestionNumber);
RadioGroup radioGroup1 = (RadioGroup)findViewById(R.id.radioGroup1);
QuestionNumber.setText(String.valueOf("Question Number :" + counter));
Log.e(LOGS, "default user set variable " + c.getString(5));
Log.e(LOGS, "real value" + c.getString(6));
System.out.println("what is the current value of the counter" + counter);
// DisplayContact(c,radio1);
DisplayRadioButton(c,radio1,radio2,radio3,question);
final String questionOneDb = c.getString(5);
String radioOneIndex = "1";
String radioTwoIndex = "2";
String radioThreeIndex = "3";
// set the first question to have the right value
if(radio1.isChecked() )
{
db.updateUserResult(counter,8);
if (questionOneDb.equals(radioOneIndex))
{
Log.e(LOGS, "correct" );
rightAnswer(c,radio1,answerCounterText);
// DisplayContact(c,radio1);
}
else
{
Log.e(LOGS, "wrong" );
}
}
if(radio2.isChecked() )
{
db.updateUserResult(counter,9);
if (questionOneDb.equals(radioTwoIndex))
{
System.out.println("is this counter being reached");
// db.updateUserResult(1, 2);
// db.updateUserResult(counter, 2);
// db.updateUserResult(recordval, 6);
Log.e(LOGS, "correct" );
rightAnswer(c,radio1,answerCounterText);
}
else
{
Log.e(LOGS, "wrong" );
}
}
if(radio3.isChecked() )
{
db.updateUserResult(counter,10);
if (questionOneDb.equals(radioThreeIndex))
{
Log.e(LOGS, "correct" );
System.out.println("you have the right answer");
rightAnswer(c,radio1,answerCounterText);
}
else
{
Log.e(LOGS, "wrong" );
}
}
}
/* when you get ot the last record you want to be able to close the db */
if (c.isAfterLast())
{
// this halts the timer when there are no questiosn left
Next.setVisibility(View.GONE);
// Previous.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "More questions available in the full version PHPExpert " , Toast.LENGTH_LONG).show();
Complete.setVisibility(View.VISIBLE);
handler.removeCallbacks(timedTask);
db.close();
intentcalls();
}
}
});
Home = (Button)findViewById(R.id.home_btn);
Home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Basic_database_questionsActivity.this,AndroidGUIActivity.class);
startActivity(i);
}
});
}
If I am not totally wrong, you have a timing issue.
First you get your first question and you show the UI (your radio buttons and stuff).
You check with the click on the Next button, if the chosen answer is right, correct?
If so, you make the mistake that you first increase the counter and then query for the question based on counter (which will be the next). After that you check if the chosen radio button is the correct one. As you already read the next question from the database, you check the chosen answer to your first question with the stored answer of the second one.
Hope that was clear.
Short tip: try to clean up some code. Don't put anything inside the onCreate() make smaller chunks so you can see and follow the code flow easier...
Try this
Cursor c1 = mDbHelper.fetAll(); \\ or whatever your method is to get data from database.
if(c1.moveToFirst()){
do{
\\ Do what you want to do with it.
}while(c1.moveToNext()); \\ this will move the cursor to next line.
}
c1.close(); \\ make sure you close it, else errors will pop up in LOGCAT.

Categories

Resources