I'm creating an Android app and everything seems to be working fine. The problem starts when I try to move some of the code to another file, in order to tide things up.
Let's say that the app has a spinner and a button. Pressing the button reads the current selected string of the Spinner and presents it with a Toast. So the code is:
Spinner spinnerOmadas=(Spinner) findViewById(R.id.spinnerOmadas);
String omada = spinnerOmadas.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), omada,Toast.LENGTH_SHORT).show();
If I keep this code in the onClick function of the button in the main activity, everything works. I want to move it to another file since I will be adding more code to it.
So I create a file buttonCalculation.java with the following code:
package com.test.example;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class buttonCalculation extends MainActivity {
public void calculate(){
Spinner spinnerOmadas=(Spinner) findViewById(R.id.spinnerOmadas);
String t1= spinnerOmadas.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), t1, Toast.LENGTH_SHORT).show();
}
}
and in the onClick method of the main activity I do this:
buttonCalculation b1 = new buttonCalculation();
b1.calculate();
There is no error according to Android Studio in my approach, but when I run the app and press the button, it crashes.
Is there something that I have to declare to be able to find the objects of the main Activity?
Aucun commentaire:
Enregistrer un commentaire