Kazuk
Kazuk

Reputation: 25

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.

Upvotes: 0

Views: 901

Answers (1)

Sam
Sam

Reputation: 86948

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)))

Upvotes: 1

Related Questions