0

In my I have a set of variables that are used in almost 90% of the code. To solve this, I'm passing it through activities using an intent and putting it as extra:

intent = new Intent(getApplicationContext(), nextActivity.class);
intent.putExtra("token",getIntent().getExtras().getString("token"));
startActivity(intent);

The problem is: since it is a bunch of variables the code sometimes get a little bit messy and I need to write the same code lines multiple times, which seems stupid.

So, my question is if there are another ways of doing that such as global variable that can be read by all activities (which also look like a dirty solution).

Thank you, Pedro.

3 Answers3

1

Save those variable values as SharedPreferences so you can access it from wherever you want within your application.

AlexTa
  • 5,133
  • 3
  • 29
  • 46
  • I have to agree with shared preferences as suggested above. Very useful for through out the app. – Greg Apr 07 '17 at 14:59
0

I would suggest to extend Application (see https://developer.android.com/reference/android/app/Application.html)

Create a new class that would look like

public class MyApplication extends Application {
//your variable here
}

specify in your AndroidManifest.xml to use MyApplication :

<application
      android:name=".package.name.MyApplication"
      ....

and to use it in your activity

((MyApplication)getApplication()).getYourStuff();
lmoor
  • 195
  • 2
  • 16
  • would be careful with this approach as it has some disadvantages which are described in this blog post [Don't Store Data in the Application Object](http://www.developerphil.com/dont-store-data-in-the-application-object/) – BrickTop Apr 07 '17 at 14:46
  • Would it be possible to override "onTerminate" and then store it in SharedPreference or something? and get them back on onCreate? would it be better for performance? I don't know if getting data from sharedPreference is faster? Thanks for the link btw, it's interesting – lmoor Apr 07 '17 at 15:30
0

If the values are fixed in those variables, create a class and declare those variables as static, final. You can then simply access those by :

ClassName.VariableName;

If the values changes everytime, use SharedPreference. Here's a link to one of my answer on using SharedPreferene

https://stackoverflow.com/a/37088866/5534549

Community
  • 1
  • 1
Basu
  • 763
  • 8
  • 27