I am developing a vocabulary application and i want to cycle array values with next and previous buttons. I assigned values from Database and working. But i cant cycle between array values. Increasing working but i have to click several times to cycle previous value. I could not find the correct increment, decrement operator.
int position = 0;
`btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position >= array.length){
position = 0;
txtWord.setText(array[position][0]);
position++;
}else {
txtWord.setText(array[position][0]);
position++;
}
}
});`
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position >= 0){
txtWord.setText(array[position--][0]);
}else{
position = array.length;
txtWord.setText(array[position--][0]);
}
}
});
Complete Code is here:
DatabaseHelper myDB;
TextView txtWord, txtNumberOfWords;
Button btnBack, btnShow, btnNext;
String[][] array;
int position = 0;
boolean showWord= true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
txtWord = (TextView)findViewById(R.id.txtWord);
txtNumberOfWords = (TextView)findViewById(R.id.txtNumberOfWords);
btnBack = (Button)findViewById(R.id.btnBack);
btnShow = (Button)findViewById(R.id.btnShow);
btnNext = (Button)findViewById(R.id.btnNext);
myDB = new DatabaseHelper(this);
Cursor data = myDB.getListContents();
array = new String[data.getCount()][2];
if(data.getCount() == 0){
Toast.makeText(MainActivity.this, "There is no definition!", Toast.LENGTH_LONG).show();
}else{
data.moveToFirst();
for(int i = 0; i < data.getCount(); i++){
for(int y = 0; y < 2; y++){
array[i][y] = data.getString(1+y);
}
data.moveToNext();
}
txtWord.setText(array[0][0]);
position = position + 1;
txtNumberOfWords.setText(position + " of " + array.length);
}
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position >= array.length){
position = 0;
txtWord.setText(array[position][0]);
position++;
txtNumberOfWords.setText(position + " of " + array.length);
}else {
txtWord.setText(array[position][0]);
position++;
txtNumberOfWords.setText(position + " of " + array.length);
}
showWord = true;
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position >= 0){
txtWord.setText(array[position--][0]);
txtNumberOfWords.setText(position + " of " + array.length);
}else{
position = array.length;
txtWord.setText(array[position--][0]);
txtNumberOfWords.setText(position + " of " + array.length);
}
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(showWord){
txtWord.setText(array[position-1][1]);
showWord = false;
}else{
txtWord.setText(array[position-1][0]);
showWord = true;
}
}
});
}