Is it possible to access an arraylist from another void then it is generated in in Java? (I'm making an android app, i did cut down the code massively)
package com.example.example;
import ...;
public class Example {
@Override
protected void onCreate(Bundle savedInstanceState) {
//android things here...
ArrayList<String> questionid = new ArrayList<String>();
questionid.add("1");
questionid.add("2");
questionid.add("3");
questionid.add("4");
questionid.add("5");
questionid.add("6");
questionid.add("7");
questionid.add("8");
questionid.add("9");
questionid.add("10");
Collections.shuffle(questionid, new Random(System.nanoTime()));
}
private void newQuestion() {
questionid.get(0); //<-- It doesn't find the arraylist questionid
}
}
private void setNewQuestion() {
TextView questionnumberlabel;
questionnumberlabel = (TextView) findViewById(R.id.questionnumber);
if (questionnumberlabel.getText().equals("1")) {
}
}
}
Is there a way to make the arraylist accessible everywhere in the class? Again, i'm developing an app for android, so i did cut down the code a bit.
You've currently declared questionid
as a local variable in the onCreate
method. That variable only exists for the duration of that method call. You want an instance variable - i.e. something which is part of the state of the object, and which is available within all methods.
public class Example {
private ArrayList<String> questionid;
@Override
protected void onCreate(Bundle savedInstanceState) {
questionid = new ArrayList<String>();
questionid.add("1");
...
}
private void newQuestion() {
String firstQuestion = questionid.get(0);
...
}
}
See more on this question at Stackoverflow