Issue
My question is simple. What method can I use to tell my program that a button is pressed? I'm trying some codelines but its not really working (I tryed with isPressed). in my logs I can read the line --> TAMAÑO DEL CONTADOR: < the numbers until it reaches max.> before I can I even place a value, so I understand the loop doesnt wait for my inputs.
Here is my code:
public class navegador extends AppCompatActivity {
public String Sdat;
public EditText ET2;
int tam;
ArrayList<String> Medidas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navegador);
ET2 = findViewById(R.id.ET1);
Button bot = findViewById(R.id.bot);
tam = getIntent().getIntExtra("numero",0);
Medidas = new ArrayList<>();
int contador = 0;
System.out.println("TAMAÑO DEL ARRAY: "+ tam);
while ( contador <= tam){
System.out.println("TAMAÑO DEL CONTADOR: " + contador);
bot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View bot) {
if(bot.isPressed()){
MeterMedida();
}
}
});
contador++;
if(contador == tam){
Toast.makeText(this, "Distancia máxima alcanzada. Toca Crear tabla.", Toast.LENGTH_SHORT).show();
}
}
}
public void MeterMedida(){
Sdat = ET2.getText().toString();
Medidas.add(Sdat);
ET2.setText("");
}
public void LanzarLista (View view){
Intent A = new Intent(this, Lista.class);
A.putStringArrayListExtra("Lista", Medidas);
startActivity(A);
}
}
Thanks a lot, ask me for more information if you think you need it.
EDIT
As usual, less is more, I removed the while, and contador variable, now it works like I wanted and its pretty much simple. Thank you so much.
Solution
You don't need a while
loop:
//a list to keep all the entered floats
private List<Float> floats = new ArrayList<Float>();
//each time you click the listener is invoked
bot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View bot) {
//every time the button is clicked, fill the current typed float
floats.add(Float.parseFloat(ET2.getText().toString()));
ET2.setText("");
}
});
Answered By - Hasan Bou Taam
Answer Checked By - Mildred Charles (JavaFixing Admin)