Question

I am making an android app that needs the user to enter a 4 digit pin from the buttons I made and later on confirm the pin. I figured I would be able to store the pin as an array.

My question is, how do I store the button pressed?

Here is what I have come up with so far

public class EnterPin extends Activity 

{

public int[] pin = new int[4];

public void PinEnterd(View view)

{

int i;

for(i = 0; i < 4; i++ )

{

pin = 

}


}

}
Was it helpful?

Solution

You need declare a variable to mark the next position of the pin. In the case of the code below, you can save the next position of your pin to ctr.

public int[] pin = new int[4];
int ctr = 0; //add this to mark the index of your pin

public void PinEnterd(View view)
{
    Button btnPressed = (Button) view; //get access to the button
    int value = Integer.parseInt(btnPressed.getText().toString()); //get the value of the button
    pin[ctr++] = value; //save inputted value and increment counter. next position after 0 is 1.
}
  • When you inputted the first pin and the value of ctr is 0, the inputted pin will be save to pin[0].
  • When you inputted the first pin and the value of ctr is 1, the inputted pin will be save to pin[1].
  • When you inputted the first pin and the value of ctr is 2, the inputted pin will be save to pin[2].
  • When you inputted the first pin and the value of ctr is 3, the inputted pin will be save to pin[3].

OTHER TIPS

Just us a boolean :

private boolean isPressed = false;

public void PinEntered(View v) {
    if(!isPressed) {
        isPressed = true;
        // Do what you like to do on a Button press here
}

If the Pin is incorrect or else and the user as to push the button again just reset isPressed to false again

how about using something like this? just get the button clicks and add the digits to the array after that you can store it in the sharedpreferences or something...

public class EnterPin extends Activity implents OnClickListener{

public int[] pin = new int[4];
public Button[] buttons;


public onCreate(...){
    buttons[0] = (Button)findViewById(R.id.b1);
    ...
    buttons[9] = (Button)findViewById(R.id.b9);

    buttons[0].addOnclickListener(this);
    ...
    buttons[9].addOnclickListener(this);
}
public ... OnClickListener(View v){
switch(v.getId()){
    case R.id.b1:
        pin[] = 0;
    break;
    ...
    case R.id.b10:
        pin[] = 9;
    break;
}


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top