Android Build a Simple Android App Basic Android Programming Generating a Random Number

I want to generate a sequential array of string instead of random.

what will be the logic if i want to generate sequential array of string like when i click next the 0th position of array will execute and after that when i click on next then 1st position of array will execute then next then 2nd position and so on.

3 Answers

public class MainActivity extends AppCompatActivity {

    private TextView mMyTextView;
    private Button mMyButton;
    public int i = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMyTextView = (TextView) findViewById(R.id.MyTextView);
        mMyButton = (Button) findViewById(R.id.MyButton);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] digit = {"One","Two","Three","Four"};
                if (i<digit.length){
                    mMyTextView.setText(digit[i]);
                    i++;
                }else{
                    i = 0;
                }
            }
        };

        mMyButton.setOnClickListener(listener);
    }
}

If you have any issue in android app development or You can check this for Android Assignment Help

changed from comment to answer

Hi Sarfaraj,

I think there's going to be a small problem with the way your code is ordered. After the last fact is shown, the next click will result in the else block being executed and that only sets the index back to 0. A new fact won't be shown.

This might work a little better:

if (i >= digit.length){
  i = 0;
}

mMyTextView.setText(digit[i]);
 i++;
Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,219 Points

Basically, in your FactBook class you would create a new member variable to store the index of the current fact being displayed. Then when you want a new fact instead of picking a random number you increment the index by 1. Also be sure to check that you don't go past the end of the array, possibly going back to the start of the list if you do.

I have a question after viewing the answer, if in the same situation i want to generate a logic for going back in sequential order. for example array is travelling from a[6] to a[7] then a[8] then a[9] and so on now as per logic if i am at a[9] and i want to go to a[8] then a[7] and so on what will be the logic?