-4

For example:

int a=5;  //in MainActivity.java
int b=7 //in MainActivity2.java
int c=8 //in MainActivity3.java   

and these three variables in another Activity i.e.

int total= a+b+c  //in MainActivity4.java
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Leena harani
  • 17
  • 1
  • 8

3 Answers3

-1

way 1: you can use public static variable.but static variable is memory leak.

public static int a=5;  //in MainActivity.java
public static int b=7 //in MainActivity2.java
public static int c=8 //in MainActivity3.java  


int total= a+b+c  //in MainActivity4.java


way 2: other way, save a,b,c in shared preference and in MainActivity4.java load there and use.

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
-1

You can just make those variables static, and can access them from MainActivity4. If you want to make these variables private and write protected, then use a static getter method.

-1

As mentioned in your code you are using

int a=5;  //in MainActivity.java
int b=7 //in MainActivity2.java
int c=8 //in MainActivity3.java   

To start activity you must be using below code

Intent intent = new Intent(this, yourRequiredActivity.class)
intent .putExtra("firstVariable", a);
intent .putExtra("secondVariable", b);
intent .putExtra("thirdVariable", c);
startActivity(myIntent);

And when new Activity starts use below code

 Intent mIntent = getIntent();
 int a= mIntent.getIntExtra("firstVariable", 0);
 int b= mIntent.getIntExtra("secondVariable", 0);
 int c= mIntent.getIntExtra("thirdVariable", 0);

And now you can use below code for your operation

int total= a+b+c 

hope that answers your question.

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
  • This is the best answer, you can also include that SharedPreferences could also be a option. – HB. Nov 12 '17 at 06:26
  • This is probably the best answer so far, however, this is very difficult to maintain as well. I'd recommend you store the data outside of intents and activity's in memory. SharedPreferences would also be valid. – spierce7 Nov 12 '17 at 06:27
  • Who is downvoting this answer? please mention the reason so I can update my answer. – Abdul Waheed Nov 12 '17 at 09:54
  • @Leenaharani I am glad that helped you :) – Abdul Waheed Nov 13 '17 at 05:22