简体   繁体   中英

How to set text in array on a textView by clicking a button that will increment the array position

Please I'm trying to get this code working. I have an array of Strings that i want to display in a textview one at a time only on button click. That is when the user clicks a button, the next string in the next array position is fetched and displayed. This is what i have. Please i need your helps.

public class  MainActivity extends Activity {

TextView tv ;
Button next ;
int j = 0 ;
String[] allQuestions ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MySQLiteHelper db = new MySQLiteHelper(this) ;



    db.addValues() ;

    allQuestions = db.getQuestions() ; //This is the array i want to fetch the data from

    tv  = (TextView) findViewById(R.id.question_id) ;
    next = (Button) findViewById(R.id.next) ;

    do{
        tv.setText(allQuestions[j]) ;

        next.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                j++ ;
                tv.setText(allQuestions[j]) ;               
            }
        }) ;

    }
    while(j < allQuestions.length) ;

}

The db.allQuestions method is found here

 public String[] getQuestions(){

        String sql = "SELECT question FROM Questions" ;

        SQLiteDatabase db = this.getReadableDatabase() ;

        Cursor cursor = db.rawQuery(sql, null) ;

        if(cursor == null){
            return null ;
        }
        else{
            String[] allQuestions  = new String[cursor.getCount()] ;

            for(int i = 0 ; i < cursor.getCount() ; i++){
                cursor.moveToNext() ;
                String question = cursor.getString(cursor.getColumnIndex("question")) ;
                allQuestions[i] = question ;
            }

            return allQuestions;
        }


    }

The database have been created and some dummy values have been added. Thanks for your help in advance.

Try this:

 next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(++j >= allQuestions.length){
                j = 0;
            }
            tv.setText(allQuestions[j]) ;               
        }
    }) ;

and remove the do{}while(); loop.

Your current code doesn't work because the setOnClickListener(...) doesn't block the execution until the onClick(...) is called (and j incremented), which means that j is not incremented and the loop keeps going (blocking the UI thread).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM