Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: Looping through a string array - help needed on logic for intent method
    primarykey
    data
    text
    <p>I'm a java novice and I've using the code below to display a list of clickable TextViews that call a specific class when they are clicked.</p> <p>It is a list of football team names.</p> <p>Eg.</p> <p>Arsenal Manchester United Chelsea</p> <p>Clicking on TextView Arsenal (TextView id = ars) will call ars.class Clicking on TextView Chelsea (TextView id = che)will call che.class</p> <p>I have over 20 football team names.</p> <p>I have an array of textview ids, which I loop through and assign them a clickable action. This works fine.</p> <p>I have an string array of teamnames, the code loops through the string array and assigns each teamname to a Class object, which is used in the Intent() method.</p> <p>When I run this code, the list is produced but when I click on a team name it always opens Wol.java, the last position in the string array. </p> <p>I need some help with the logic, so that when I click on Arsenal it opens ars.class</p> <p>Here is the code.</p> <pre><code>public final int[] teams = { R.id.ars, R.id.ast, R.id.bir, R.id.bla, R.id.blp, R.id.bol, R.id.che, R.id.eve, R.id.ful, R.id.hul, R.id.lee, R.id.liv, R.id.mid, R.id.mnc, R.id.mnu, R.id.nor, R.id.nwu, R.id.por, R.id.qpr, R.id.sto, R.id.sun, R.id.swa, R.id.tot, R.id.wes, R.id.wig, R.id.wol }; //String array of teamnames, named to correspond their class name. public final String[] teamnames = { "ars", "ast", "bir", "bla", "blp", "bol", "che", "eve", "ful", "hul", "lee", "liv", "mid", "mnc", "mnu", "nor", "nwu", "por", "qpr", "sto", "sun", "swa", "tot", "wes", "wig", "wol" }; TextView tv; Class classname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.m_transfers); setTeamNames(); //Method sets up team names to a Class name. for (int i = 0; i &lt; teams.length; i++) { tv = (TextView) findViewById(teams[i]); tv.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent open = new Intent(Transfers.this, classname); startActivity(open); } }); } ; } public void setTeamNames() { for (String s : teamnames) { String name = "ttj.android.ft.teams." + s; try { classname = Class.forName(name); } catch (ClassNotFoundException e) { e.printStackTrace(); } } ; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload