I have a activity in Android Studio and the app closes whenever I start that activity. Can you please check what’s the problem.
public class AddEx extends AppCompatActivity {
public int max, min;
public int w,m;
public ArrayList<Object>exer = new ArrayList<>();
public ArrayList<Integer>ans = new ArrayList<>();
public ListView ex = findViewById(R.id.Exerciselist);
public ArrayAdapter<Object> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.select_dialog_item, exer);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_ex);
start();
}
public void start()
{
for (int i = 0; i<=9; i++)
{
Intent intent = getIntent();
int Token = Integer.parseInt(intent.getStringExtra(Add_Subtract.MSG));
if(Token == 1)
{
max = 9;
min = 1;
}
else if(Token == 2)
{
max = 99;
min = 10;
}
else if(Token == 3)
{
max = 999;
min = 100;
}
else if(Token == 4)
{
max = 9999;
min = 1000;
}
else if(Token == 5)
{
max = 99999;
min = 10000;
}
w = ((int) Math.floor(Math.random() * (max - min + 1) + min));
m = (int)Math.floor(Math.random() * (max - min + 1) + min);
ans.add(w+m);
exer.add(w+" + "+m);
}
ex.setAdapter(arrayAdapter);
}
public void answers(View view)
{
for (int i = 0; i<=9; i++)
{
Object ques = exer.get(i);
exer.set(i, ques+" = "+ans.get(i));
}
ex.setAdapter(arrayAdapter);
}
}
The function answers is button controlled. I want the start function to run as the activity starts but as soon the activity starts, the app closes. I request you to tell the problem
Thanks
2
Answers
public ListView ex = findViewById(R.id.Exerciselist);
Remove this line and add it to either
onCreate()
orstart()
You are initialising
Exerciselist
even before the layout is initialised, so the app doesn’t know what it is, that’s why it crashes// move the list view attach to here
// move the array adapter here