Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a simple variable value for use in another class in Android

Tags:

android

What is the correct way to pass a simple variable which has its value set to use in another class? I have a counter which is incremented with a button press and when counter = 3 a method is called which loads another activity which loads another screen with a string which states the button was pressed. Here is where I want to include the number 3 passed from the counter variable in the previous class, but I am not sure the correct way to do this. I tried creating an instance of the class and connecting to the variable that way but the value is never passed and it is always 0.

like image 845
deucalion0 Avatar asked Mar 02 '26 06:03

deucalion0


2 Answers

Try following code,

public class First
{
   private static int myVarible = 0;


    private void myMethod()
    {
         myVariable = 5; // Assigning a value;
    }

    public static int getVariable()
    {
        return myVariable;
    }
}

public class Second
{
    int i = First.getVariable();  // Accessing in Another class
}
like image 168
Altaaf Avatar answered Mar 03 '26 19:03

Altaaf


You may pass value via Intent - resource bundle.

Pass value from current activity,

Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("no",10);
startActivity(intent);

and in ResultActivity (onCreate),

Bundle bundle=getIntent().getExtras();
int value=bundle.getInt("no");

In case of non-activity classes, you may define a public method.

For instance,

public Integer getValue() //returns a value
{
  return 10;
}

Or

public void setValue(Integer value)
{
  ...
}
like image 44
KV Prajapati Avatar answered Mar 03 '26 19:03

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!