3

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.

1

5 Answers 5

10

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly! Thank you! I knew it would be simple, but I couldn't figure it out.
5

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)
{
  ...
}

Comments

1

one way to do it would be when you build your new intent to do :

Intent itn = new Intent(...,...);
itn.putExtra(KEY,VALUE);
startctivity(itn);

And on the other class do something like :

this.getIntent.getStringExtra(KEY);
or
this.getIntent.getWHATEVERYOURVARIABLEWASExtra(KEY);

Hope it helps you, and it's the better way to pass arguments between 2 activities :)

Comments

1

You can also do it through define variable as "static" in one activity and in second activity use that variable with using <<classname>>.<<variableb>>

ex:

Activity1:

Static var = 5;

Activity2:

System.out.println(Activity1.var);

Comments

1

You can pass that value using the intent

Intent new_intent=new Intent(this,SecondActivity.class);
intent.putExtra("counter",10); //here the value is integer so you use the  new_intent.putExtra(String name,int value)
startActivity(new_intent);

After that in the second activity class you can get that that values using Bundle

Bundle bundle = getIntent().getExtras();
int count = bundle.getInt("counter");

I think this may help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.