Tek Tek - 8 months ago 19
Android Question

Moving code to another class leads to app crash

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();

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?


I think the problem is with the function findViewById() as you do not have any layout defined in your buttonCalculation class. Therefore you have to pass it as a parameter.

public class ButtonCalculation { //I don't find any reason to extend MainActivity here

    //also you need a constructor (except if you are using a static method)
    public void ButtonCalculation (){


    public void calculate(ViewGroup root, Context context){

        Spinner spinnerOmadas=(Spinner) root.findViewById(R.id.spinnerOmadas);
        String t1= spinnerOmadas.getSelectedItem().toString();

        Toast.makeText(context, t1, Toast.LENGTH_SHORT).show();



And in your MainActivity

final ViewGroup root= (ViewGroup) ((ViewGroup) this
ButtonCalculation b1 = new ButtonCalculation ();
b1.calculate(root, getApplicationContext());