Calling Method from other Java Class - java

My slot machine is still in progress. I am trying to get a method from one class to another but I can't figure it out. Could anyone please help me? Here is my first code which I wanted to call the method from the other class:
GameMainActivity:
package com.ics136leeward.slotmachine;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class GameMainActivity extends Activity {
ViewFlipper slotOne, slotTwo, slotThree, spinStop;
Button spin, stop, bet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
this.initSpin();
this.initStop();
}
private void initSpin() { //initialize Spin Method
spin = (Button) findViewById (R.id.spinBtn);
slotOne = (ViewFlipper) findViewById (R.id.slot1);
slotTwo = (ViewFlipper) findViewById (R.id.slot2);
slotThree = (ViewFlipper) findViewById (R.id.slot3);
spinStop = (ViewFlipper) findViewById (R.id.spinstopbutton);
spin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.setFlipInterval(40);
slotOne.startFlipping(); //slot 1 spin
slotTwo.setFlipInterval(50);
slotTwo.startFlipping(); //slot 2 spin
slotThree.setFlipInterval(60);
slotThree.startFlipping(); //slot 3 spin
spinStop.showNext(); // shows the stop button
}
});
}
private void initStop() { //initialize Stop Method
stop = (Button) findViewById (R.id.stopBtn);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.stopFlipping(); //stops slot 1
slotTwo.stopFlipping(); //stops slot 2
slotThree.stopFlipping(); //stops slot 3
spinStop.showNext(); //shows the spin button again
if(slotOne == slotTwo || slotTwo == slotThree) {
}
}
});
}
}
Here is the second java class which I wanted to call the method getBet1() and getBet5() to the first activity:
Bet:
package com.ics136leeward.slotmachine;
import android.app.Activity;
import android.widget.TextView;
public class Bet extends Activity {
TextView userBet, bankRoll, event;
final int BETONE = 1, BETFIVE = 5;
int uBet = 100, bet;
public void getBet1() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETONE;
bet += BETONE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
public void getBet5() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETFIVE;
bet += BETFIVE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
}

You need to make a Utility class not a Activity class
So change
public class Bet extends Activity {
to
public class Bet // Normal java class
Since its not a Activity class there is not need to initialize views
userBet = (TextView) findViewById (R.id.userBet); //remove them
// Initialize all yours views in Activity
Now in Activity class
Bet bet = new Bet();
int value =bet.getBet1();
In getBet1() do you calculations an return values.
Then in Activity you can set the value to TextView
textView.setText(String.valueOf(value));
Do also check raghav's answer #
Can i Create the object of a activity in other class?

you can define those method static and then call by its class name like
Bet.getBet1();
Bet.getBet5();
or simply you can create class object and then call it
Bet b = new Bet();
b.getBet1()

Note: You don't need to extend to Activity class as you are not using any UI. (Already suggested by Raghunandan)
Try this code in the onCreate method of your calling class i.e. GameMainActivity
Bet bet= new Bet(); // where bet is object of Bet Class
bet.getBet1();
bet.getBet5();
However, You can create the object of Bet class in any method and access the class methods provided their access modifier must be public.

Related

Why is this MainActivity class code working?

I am writing tic tac toe game in which i am calling imageTapped when image is tapped to change its image to cross and then it calling aiturn to find valid move and change its image to circle. Now my question is how did calling non static method aiturn from non static method imageTapped works without creating its object.
package com.example.kapil.tictactoe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private GameLogic gameLogic;
LinearLayout linearLayout;
TextView label;
public void imageTapped (View view) {
ImageView image = (ImageView) view;
label = findViewById(R.id.label);
String pos = image.getTag().toString();
//if button is already tapped
if (! gameLogic.setImage(Integer.valueOf(pos)))
return;
image.setImageResource(R.drawable.cross);
//return 1 for win 2 for draw otherwise 0
int win = gameLogic.logic();
if (win == 1) {
label.setText("You Win!!");
gameLogic.gameOver();
return;
} else if (win == 2) {
label.setText("Game Draws!!");
return;
}
aiturn();
}
public void aiturn () {
int move = gameLogic.aiMove();//return best move between 0 to 8
int rowNum = move/3;
int colNum = move%3;
if (rowNum == 0) {
linearLayout = findViewById(R.id.line1);
} else if (rowNum == 1) {
linearLayout = findViewById(R.id.line2);
} else if (rowNum == 2) {
linearLayout = findViewById(R.id.line3);
}
((ImageView) linearLayout.getChildAt(colNum)).setImageResource(R.drawable.circle);
label = findViewById(R.id.label);
//return 1 for win 2 for draw otherwise 0
int win = gameLogic.logic();
if (win == 1) {
label.setText("AI wins!!");
gameLogic.gameOver();
} else if (win == 2) {
label.setText("Game Draws!!");
}
}
//if play again button is pressed
public void Reset (View view) {
gameLogic.reset();
TextView label = findViewById(R.id.label);
label.setText("");
int ids[] = {R.id.line1,R.id.line2,R.id.line3};
for (int k=0;k<ids.length;k++) {
LinearLayout linearLayout = findViewById(ids[k]);
for (int i = 0; i < linearLayout.getChildCount(); i++) {
((ImageView) linearLayout.getChildAt(i)).setImageResource(R.mipmap.ic_launcher);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gameLogic = new GameLogic();
}
}
This works because the Android framework creates the instances of Activities.
Now my question is how did calling non static method aiturn from non static method imageTapped works without creating its object.
Android apps are not launched using a public static void main(...) method like a classic Java app.
Instead, when your app is launched, the Android framework automatically creates instances of your app's Activity classes, and wires them up to the user interface (as per the XML file).
Then, when the user "taps", the framework calls the imageTapped method on the (existing) activity object. That then calls aiturn on the same object.
Or at least, I think that is the intent of the person who wrote that code. In reality, the imageTapped method doesn't appear to be an API method in the superclass hierarchy of your MainActivity class. So I suspect that it won't be called.
I'm not sure what you are actually trying to do, but maybe you should override onTouchEvent(...)

Class variable random number... always the same? Android.

I am working through a Udemy course and we're building a basic "Higher or Lower" app. My app essentially works, however the random number it chooses for us to guess is always the same no matter how many times I destroy and relaunch the activity.
My MainActivity.java:
//mad import statements here
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
protected int generateNum(){
Random rand = new Random();
int randNum = rand.nextInt(100);
return randNum;
}
protected void numberEval(View view) {
EditText enteredNumber = (EditText) findViewById(R.id.numberEntry);
String numberString = enteredNumber.getText().toString();
Button pressMe = (Button) findViewById(R.id.button);
int numToEval = Integer.parseInt(numberString);
String result;
TextView showWinLose = (TextView) findViewById(R.id.winLoseText);
if (numToEval > correctNumber) {
result = "Too high!";
} else if (numToEval < correctNumber) {
result = "Too Low!";
}else {
result = "You guessed it!";
}
showWinLose.setText(result);
}
}
Super super basic, yes? Originally, my numberEval() method called generateNum(), but then I realized it was generating a new number to guess every time I pressed the button. So I set it the way it was here, where onCreate() generates correctNumber only once and correctNumber is now a class variable. Now it doesn't generate a new number every button click, but it won't seem to generate a new number at all. It's stuck at 0 no matter how any times I launch, close, relaunch, etc. the app.
How can I fix this? Thanks in advance.
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
// ...
}
The last line in onCreate() declares a local variable named correctNumber. This hides the class field with the same name and is only available inside onCreate(). To fix the problem, remove int from this line so that you use the class field instead.

My Simple Interest calculator is crashing with a null pointer exception error

My Simple Interest calculator is crashing with a null pointer exception error, not sure what the problem is, there are no errors in the IDE before I complile, this is new to me. Here is my code and logcat: edit: Icouldn't post a logcat as the editor thinks it's code and I can't get it to format correctly
Code:
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity
implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private int years;
private TextView YT;
private SeekBar bar;
private EditText principal = (EditText) findViewById(R.id.PA_field);
private EditText interest = (EditText) findViewById(R.id.IR_field);
public EditText pvalue;
public EditText ivalue;
private double mPvalue = 0;
private double mIvalue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
bar = (SeekBar)findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
pvalue = (EditText) principal.getText();
ivalue = (EditText) interest.getText();
String s = principal.getText().toString();
mPvalue = Double.parseDouble(s);
String s2 = interest.getText().toString();
mIvalue = Double.parseDouble(s2);
}
#Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
#Override
public void onStartTrackingTouch (SeekBar seekBar){
}
#Override
public void onStopTrackingTouch (SeekBar seekBar){
}
#Override
public void onClick(View view) {
TextView fTextView = (TextView) findViewById(R.id.finalText);
double finValue = mPvalue * (mIvalue/100) * years;
fTextView.setText("The interest for " + pvalue + "at a rate of " + ivalue + "for " + years + "year(s) is " + finValue);
}
}
You can't instantiate view variables by calling findViewById as you're declaring them. You have to declare them first and then instantiate either in onCreate or some method invoked after the Activity is bound with the view. Make sure to do it after setContentView(R.layout.sicalculator);
Okay, after seeing your layout, stacktrace and reading more in to your code, I saw that there are fundamental issues which ought to give you more crashes, so let's fix them.
First, pvalue and ivalue variables are unnecessary! Remove them.
Related: You cannot assign an Editable to an EditText. So this line is invalid ivalue = (EditText) interest.getText(); Because getText() returns an Editable. But these are all redundant and unnecessary anyways.
Second, in onCreate method, let's just initialize views and not try to get values and parse them yet; the user (or you) haven't interacted nor entered any values there yet; so trying to parse null values in to Doubles will crash your app.
Your onCreate method should look something like this. (Note that I'm also initializing your button and setting the click listener here).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
principal = (EditText) findViewById(R.id.PA_field);
interest = (EditText) findViewById(R.id.IR_field);
bar = (SeekBar) findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
calcBtn = (Button)findViewById(R.id.calc_btn);
calcBtn.setOnClickListener(this);
}
Now, you should get the values and parse them in your onClick listener - only when the user has entered values and clicked on the Calculate button, so your onClick() method should look something like this:
#Override
public void onClick(View view)
{
TextView fTextView = (TextView) findViewById(R.id.finalText);
mPvalue = Double.valueOf(principal.getText().toString());
mIvalue = Double.valueOf(interest.getText().toString());
double finValue = mPvalue * (mIvalue / 100) * years;
fTextView.setText("The interest for " + mPvalue + "at a rate of " + mIvalue + "for " + years + "year(s) is " + finValue);
}
And that should clear the logic and order or declaring, initializing, retrieving values from variables for you. I hope this explains how Java and Android basics work.
Oh by the way, I actually ran the code and it's running on my phone so this isn't just off the top of my head. If this helped you, please accept the answer.
Best wishes,

Android variable availability (can not be resolved)

While trying to run my app, I noticed that a few errors claiming that many variables can not be resolved, even though declared in the code
i changed it to the following code, but once I enter the app, it collapses:
public String GetErr(){
String error="";
if(Facebook_name.toString().equals("")&& Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name.toString().equals(""))
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id.toString().equals(""))
error+="Id entered is invalid/n";
if(Pass.toString().length()<5 || Pass.toString().equals(""))
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
EDIT: Now the geterr() returns an empty string at all times.
You are declaring variables in the onCreate() method, so that is their scope. You can not use them outside this function. So when you use them in the GetErr() method, you get an error. You can solve this by moving the variables you need in multiple methods to global variables (so declare them in the class instead of in the method.
Edit
package com.example.app;
//import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
//import android.widget.DatePicker;
import android.widget.TextView;
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
Button Btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Btn1 = (Button) findViewById(R.id.Btn1);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
Btn1.setOnClickListener(this);
Facebook_chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(Facebook_chk.isChecked())
Facebook_name.setEnabled(true);
else
Facebook_name.setEnabled(false);
;
}
});
}
public String GetErr(){
String error="";
if(Facebook_name==null && Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name==null)
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id==null)
error+="Id entered is invalid/n";
if(Pass.toString().length()<5)
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
#Override
public void onClick(View v) {
if(v == Btn1){
String err = GetErr();
if(err != ""){
Txterr.setText(err);
}
}
}
}
define:
CheckBox Facebook_chk
TextView Facebook_name
TextView Name
TextView Id
TextView Txterr
TextView Pass
As Global Variables, like:
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
...
}
...
}
UPDATE:
If you would like to make a View to respond for Click Event, you'll need to make sure you've set that View clickable.
Since you did:
View v = findViewById(R.id.Btn1);
v.setOnClickListener((OnClickListener) this);
I've no idea R.id.Btn1 is really a Button or just a View. If it is a Button, please change to:
Button button = findViewById(R.id.Btn1);
button.setOnClickListener(this);
If it's not a button, just some View and you want it to respond to your Click, please add one line after findViewById
v.setClickable(true);
Again, if you intend to use this v sometime later in your code, you need to declare it as a global variable just like you did on your TextViews
Ref public void setClickable (boolean clickable)

NullPointerException after changing class ( Code worked before )

I'm doing basic calculator for Android in Java. My calculator worked but i had all code in one class. Then i wanted to make code more readable and i created another Calculation class and i put calculation code in there. And now for some reason my app crashes. LogCat says: NullPointerException. (My app starts fine and then when i choose desirable currency to convert and when i click on ImageButton(convert) then app crashes). Here is my code:
CroToEu class:
package com.eu.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class CroToEur extends Activity {
TextView resultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cro_to_eur);
final ImageButton convert = (ImageButton) findViewById(R.id.converButton);
convertButton(convert);
}
private void convertButton(final ImageButton convert) {
resultView = (TextView) findViewById(R.id.resultView);
convert.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Calculate now = new Calculate();
now.croToEu();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
convert.setImageResource(R.drawable.convert_button_ontouch);
checkForEmptyEntry();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
convert.setImageResource(R.drawable.convert_button);
}
return false;
}
private void checkForEmptyEntry() {
if(Calculate.HRKfield.getText() == null || "".equals(Calculate.HRKfield.getText().toString())) {
resultView.setText("You left empty field");
} else {
resultView.setText(Calculate.HRKfield.getText()+" HRK = "+Calculate.fixDecimal+" EUR");
}
}
});
}
}
And my calculation class:
package com.eu.calculator;
import java.math.BigDecimal;
import android.app.Activity;
import android.widget.EditText;
public class Calculate extends Activity {
public static EditText HRKfield; //S tem dobimo vrednost iz polja edittext
public static double EUR = 0.133;//drži vrednost
public static Double HRK; // Možnost uporabe double za parsing
public static double result; // rezultat
public static BigDecimal fixDecimal; // rezultat pretvori na decimalko
public BigDecimal croToEu() {
HRKfield = (EditText) findViewById(R.id.enterField);
try {
HRK = Double.parseDouble(HRKfield.getText().toString()); //tukaj dobimo čisto številko, ki jo uporabnik vnese v polje
result = HRK * EUR;
fixDecimal = new BigDecimal(result);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
} catch (NumberFormatException e) {
}
return fixDecimal;
}
}
Don' t extend Calculate class with Activity . Remove extends Activity in Calculate class
If you are trying to just create a helper class whcih does the calculation for you then don't extend Activity on your Calculate class. Instead get your croToEu method to return a variable and call this from the other class as follows.
Calculate now = new Calculate();
BigDecimal val = now.croToEu();
Id actually have the caluclate class as follows
public abstract class Calculate {
public static final double EUR = 0.133;//drži vrednost
public static BigDecimal croToEu(double hrkValue) {
BigDecimal fixDecimal = new BigDecimal(hrkValue * EUR);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
return fixDecimal;
}
}
Then in your main activity class call
BigDecimal val = Calculate.croToEu(hrkValue);
if(Calculate.HRKfield.getText() == null || "
this is wrong to get the view of other activity .........
you are in CroToEur and your acessing the HRKfield of Calculate activity which will be null
So should pass the data from CroToEur activity to Calculate activity using intent and set that in HRKfield in onCreate of CroToEur
You are missing your onCreate() method and even setContentView in Calculate.class and so it cannot find your edittext HRKfield, and so it is throwing NullpointerException

Categories

Resources