简体   繁体   中英

Using values in different activities

I'm trying to build an app which has a start screen with buttons leading to several different activities. In one of the activities subsequent to the start screen I get int values which I would like to use in another subsequent activity. From what I've seen values usually get passed between activities using bundles and intents sort of like this:

Intent i = new Intent(this, ActivityTwo.class); AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete); String getrec=textView.getText().toString();

//Create the bundle Bundle bundle = new Bundle();

//Add your data to bundle bundle.putString(“stuff”, getrec);

//Add the bundle to the intent i.putExtras(bundle);

//Fire that second activity startActivity(i);

and adding this in the second:

//Get the bundle Bundle bundle = getIntent().getExtras();

//Extract the data… String stuff = bundle.getString(“stuff”);

However I don't want my third activity to get started from the second one, is there a way to send a value without starting the other activity it is going to get used? If not should I pass the values to the start screen activity and from there to the other one and if so how?

There are a couple of ways to store data in Android. Depending on the type of data different situations may apply:

1. Shared Preferences

Stores data in key value pairs. Here's some code

Saving Values:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
  editor.commit();

Retrieving values:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);

2. SQLite Databases

This is a relational database for storing information Here's a tutorial.

I've gone into detail on the two that apply in this case, but you can check out the rest over here https://developer.android.com/guide/topics/data/data-storage.html

you can declare public static variable and access it anywhere in app but its not a good practice try using . Another way is you can use sharedpreference to store that value

It seems as though you have data you want persisted throughout your application.

Read into an SQLite Database or a Realm Database.

I have more experience using Realm databases so that would be my choice.

https://sqlite.org/

https://realm.io/docs/java/latest/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM