Open an activity by clicking on an item in a list view

0

I'm a bit lost already, I want when I click on an item in the list it opens another activity, but I only get toast ... I'm a beginner so if you can help me thank you.

public class estatisticas extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_estatisticas);
    int position = getIntent().getIntExtra("a", 1);

    final ListView lista =  findViewById(R.id.Listview);
    final ArrayList<String> estatisticas = preencherdados();

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, estatisticas);
    lista.setAdapter(arrayAdapter);

    lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            estatisticas artilheiros = (estatisticas) lista.getItemAtPosition(1);
            Intent it = new Intent(estatisticas.this, artilheiros.class);
            startActivity(it);
            it.putExtra("a", position = 1);
        }
    });


}

private ArrayList<String> preencherdados() {
    ArrayList<String> dados = new ArrayList<String>();

    dados.add("TOP 15 ARTILHEIROS");
    dados.add("Campeões");
    return dados;
}

}

    
asked by anonymous 25.12.2018 / 07:19

1 answer

0

I should assume that your intention was to get the position through the Intent, but you are initiating the activity before passing the data through the Intent, the correct one is to call putExtra () before starting the activity, this should resolve:

lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent it = new Intent(estatisticas.this, artilheiros.class);
            it.putExtra("a", position);
            startActivity(it);
        }
    });

It is a good practice not to create classes that begin with lowercase as described by oracle and the name should be the same as your .java file, this helps keep the readability of your source code.

Edited

If you want to open an activity for the item clicked then just use position which returns the position of the item in the list, when you assign the value 1 in position = 1 it will always be the item that is in position 1 of the list .

    
25.12.2018 / 12:32