Domanda

I'm new to android and I am making an app as part of an assignment, and can't get this function to return a value - the app closes and I get an error message: "Unfortunately, APP has stopped".

I have two classes, one is the MainActivity and one is a class that I am wanting to use to do arithmetic, and they are:

import com.calc.Calculation;

public class MainActivity extends Activity {
  private Calculation util;   
  calculate = (Button) findViewById(R.id.btnCalc);
  private TextView tvMultiply;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      tvMultiply = (TextView) findViewById(R.id.tvMult);
   }

  btnCalc.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    tvMiltiply.setText(String.valueOf(util.CalculateMult(4,6)));
    }
  });
}

and

package com.calc;

public class Calculation{

    public int CalculateMult(int numOne, int numTwo)
    {
    return numOne * numTwo;
    }

}

I've tried a few alternatives but to no avail. It's going to be something simple that I am not doing quite right.

Any help appreciated.

Thanks

È stato utile?

Soluzione

You need to create instance to the class before acccessing the member.

 private Calculation util = new Calculation() 

Else make the method in the class as static and access without creating instance.

This would be done by defining the class as:

package com.calc;

public class Calculation{

    public static int CalculateMult(int numOne, int numTwo)
    {
        return numOne * numTwo;
    }

}

and calling the method as:

Calculation.CalculateMult(4,6)

Altri suggerimenti

You should move the line

  calculate = (Button) findViewById(R.id.btnCalc);

to the onCreate() function after you have set the content view. You should also move the assignment of the onClickListener to your button to the onCreate() method.

Finally, you should initialize your Calculation object by using the new operator in onCreate(), i.e:

util = new Calculation();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top