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)))
Related
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.
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:)
I am getting a problem in android textview.
I am simply setting text on the android textview like below
pAmount.setText("Rs." + receiptAmount + "/-");
but is showing null in the text
System.out.println("receiptAmount ====>"+ receiptAmount );
I had tried to print the value of receiptAmount to check whether, the value is null or not.
But, It is showing the right value in the log.
What is the issue does any body have any idea.
similarly , other texview are showing the null value in the same activity.
TextView pAmount= (TextView) findViewById(R.id.amount);
1.Call the set text After Declaring the above line in Oncreate.
2.get the Proper data in receiptAmount. Your Problem Solved
pAmount.setText("Rs." + receiptAmount + "/-");
public void FeeGetFeeTypes(String studentId, String fee_slotid) {
// TODO Auto-generated method stub
ArrayList<String> arrayList_FeeType=new ArrayList<String>();
ArrayList<String> arrayList_FeeTypeAmount=new ArrayList<String>();
try{
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "select * from feetype where student_id=? and slot_id=?";
Cursor res = db.rawQuery(MY_QUERY, new String[]{ studentId, fee_slotid });
res.moveToFirst();
while (res.isAfterLast() == false){
arrayList_FeeType.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPE)));
arrayList_FeeTypeAmount.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPEAMOUNT)));
}
if(arrayList_FeeType.size()>0){
PrintActivity.sendFeeType(arrayList_FeeType, arrayList_FeeTypeAmount);
}
}
catch(Exception e){
e.printStackTrace();
}
}
This is the code that is resulting the null values. When the data is large, I get out of memory exception
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.
I have a List View that Displays songs in alphebetical order being populated by this method
public void updatelist(){
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
int j =0;
if(cursor.moveToFirst()){
do{
int ALBUM_ID = cursor.getInt((cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM_ID)));
int pathcolumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String path1 = cursor.getString(pathcolumn);
String album_url = null;
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, ALBUM_ID);
album_url = uri.toString();
ContentResolver res = this.getContentResolver();
// Album
String album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM));
String year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
// String year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS));
// artist
String artist_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST));
// display name
String DisplayName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
//title
String Title = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE));
songtitle.add(Title);
Collections.sort(songtitle);
artistname.add(songtitle.indexOf(Title), artist_name);
albumname.add(songtitle.indexOf(Title), album_name);
path.add(songtitle.indexOf(Title),path1);
albumartwork.add(songtitle.indexOf(Title),album_url);
j++;
}while(cursor.moveToNext());
}
Collections.sort(songtitle);
adapter = new ArrayAdapter<String>(this,R.layout.song,songtitle);
setListAdapter(adapter);
}
My Question is i want to insert Dividers whenever the first letter of the SongName Changes.
I have this method to get the first letter of the songname if it is different than the previous..
private void alphebetdividers(ArrayList<String> songtitle2) {
String newString = null;
// TODO Auto-generated method stub
ArrayList<Character> letters = new ArrayList<Character>();
int i = 0;
int j = 0;
while( j < songtitle.size()-1){
if(songtitle2.get(i).charAt(0) == songtitle2.get(i+1).charAt(0)){
Toast.makeText(getApplication(), songtitle2.get(i).charAt(0) + "== " + songtitle2.get(i+1).charAt(0), Toast.LENGTH_LONG).show();
}else{
// Display Char with TextView
String songName = songtitle2.get(i);
newString = songName.substring(0, 1);
}
j++;
i++;
}
How would i display this in the list view at the appropriate spots. Thank you and i will give u a good rating if u know the answer.
You probably want an Adapter that implements SectionIndexer, specifically AlphabetIndexer. See this or this.
You really should be using an Adapter... there are libraries that do all of this work for you, you shouldn't have to do it yourself in a massive loop!
Here is some sample code to help you get started... note that it is a little out-dated in that it makes use of some deprecated methods (such as managedQuery, etc.). If you wanted to be entirely 100% correct you would want to make use of the LoaderManager.LoaderCallbacks<Cursor interface introduced in the Honeycomb release, but it's a good start.
To sort the displayed views, you can make use of the sortOrder argument in the ContentProvider's query method.