Get value from one activity to another one - android

How can I use savePreferences and loadPreferences methods
In first activity
private static final String GLOBAL_PREFERENCES = "music_status";
public static void savePreferences(#NonNull Context context, String key, int value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}...
protected void onResume() {
super.onResume();
musicGroup = (RadioGroup) findViewById(R.id.radioGroupForMusic);
turnOn = (RadioButton) findViewById(R.id.radioButtonMusicOn);
turnOff = (RadioButton) findViewById(R.id.radioButtonMusicOff);
musicGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.radioButtonMusicOff:
mediaPlayer.pause();
savePreferences(MainMenuActivity.this,"music_status",0);
case R.id.radioButtonMusicOn:
mediaPlayer.start();
savePreferences(MainMenuActivity.this,"music_status",1);
}
}
});
}
In Second activity
private static final String GLOBAL_PREFERENCES = "music_status";
public static int loadPreferences(#NonNull Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultValue);
}
However I do not know how to get the value from first activity

The short answer is you cannot do that. Unless your status variable is static. Which is extremely bad for this case.
You have three choices.
SharedPreferences
In contrast to my previous revision. This might be the best option for your case.
If you only want to save the state of something, you might find it better to simply not use a class to hold the status of your music. You could do as #cricket_007 suggests and implement SharedPreferences.
You could use these example functions:
private static final String GLOBAL_PREFERENCES = "a.nice.identifier.for.your.preferences.goes.here";
public static void savePreferences(#NonNull Context context, String key, int value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
public static int loadPreferences(#NonNull Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultValue);
}
You can then use those functions in your code to save the status of your music. Instead of status.setStatus(0); and status.setStatus(1); your can use Utils.savePreferences(context, "music_status", 1); and instead of status.getStatus() you could use Utils.loadPreferences(context, "music_status", 0);
Parcelable
One option for you is to implement Parcelable in your musicStatus class. You can then send the object through an Intent to your second activity. You may find an example class implementing Parcelable below.
Once you have that, you can pass it through Intents like so:
musicStatus status = new musicStatus();
status.setStatus(8);
Intent intent = new Intent(this, HighScoreActivity.class);
intent.putExtra("status", status);
startActivity(intent);
Class implementation:
public class musicStatus implements Parcelable {
private int status;
public int getStatus() {
return status;
}
public void setStatus(int status){
this.status = status;
}
private musicStatus(Parcel in) {
status = in.readInt();
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(status);
}
public static final Parcelable.Creator<musicStatus> CREATOR = new Parcelable.Creator<musicStatus>() {
public musicStatus createFromParcel(Parcel in) {
return new musicStatus(in);
}
public musicStatus[] newArray(int size) {
return new musicStatus[size];
}
};
public int describeContents() {
return 0;
}
}
Singleton
In this case, this would really be an anti-pattern. However, it is still a possibility.
public class musicStatus {
private static musicStatus mInstance = null;
private int status;
#NonNull
public static musicStatus getInstance() {
if (mInstance == null) {
synchronized(mInstance) {
if (mInstance == null) {
mInstance = new musicStatus();
}
}
}
}
public int getStatus(){
return status;
}
public void setStatus(int status){
this.status = status;
}
}

For the easiest way, your musicStatus class need implement Serializable.
Bundle bundle = new Bundle();
bundle.putSerializable("musicStatus", status);
intent.putExtras(bundle);
in other activity:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
musicStatus status=
(musicStatus)bundle.getSerializable("musicStatus");

extend Serviceable in you POJO class.
After while starting Activity 2.
intetn.putExtra("obj",pojoObj);
and get it in you second activity using.
PojoCls obj = (PojoCls)getIntent().getSerializableExtra("obj");
Thats it.

Related

Getting a SharedPreference value in a non-activity class from a fragment

I'm trying to access SharedPreferences values in non-activity class. Preferences are defined and saved in fragment. There are three values I'm getting from seek bars, one for each of the red, green and blue color. Seek bar goes from 0 to 255 and SharedPreferences work, value is saved when I exit the app.
I'm trying to get the values in other class and then send them with POST request, but I'm sure how to get them. Can you help me?
Fragment:
public class SettingsFragment extends Fragment {
public static SharedPreferences preferences;
public static SharedPreferences.Editor editor;
public static final String RED_PROG = "RED_BAR";
public static int redValue;
public static final String GREEN_PROG = "GREEN_BAR";
public static int greenValue;
public static final String BLUE_PROG = "BLUE_BAR";
public static int blueValue;
public static final String DIMMER_PROG = "DIMMER_BAR";
public static int dimmerValue;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_settings, container, false);
preferences = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
getRedBar();
getGreenBar();
getBlueBar();
return view;
}
public void onResume() {
super.onResume();
redBar.setProgress(preferences.getInt(RED_PROG,0));
greenBar.setProgress(preferences.getInt(GREEN_PROG,0));
blueBar.setProgress(preferences.getInt(BLUE_PROG,0));
dimmerBar.setProgress(preferences.getInt(DIMMER_PROG,0));
}
public void onPause() {
super.onPause();
editor = preferences.edit();
redValue = redBar.getProgress();
greenValue = greenBar.getProgress();
blueValue = blueBar.getProgress();
dimmerValue = dimmerBar.getProgress();
editor.putInt(RED_PROG, redValue);
editor.putInt(GREEN_PROG, greenValue);
editor.putInt(BLUE_PROG, blueValue);
editor.putInt(DIMMER_PROG, dimmerValue);
editor.commit();
}
}
Other class (color values should be in RgbCapability insted of zeroes):
public class ContextCommunication {
public static void sendPref(){
RgbCapability rgbCapability = new RgbCapability(0,0,0);
Light light = new Light(true,rgbCapability, 0);
Post post = new Post("Zagreb", light);
Call<Post> call = MainActivity.apiService.savePost(post);
textViewResult.setText(post.toString());
call.enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (!response.isSuccessful()) {
textViewResult.setText(response.code());
return;
}
Post postResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "location: " + postResponse.getLocation() + "\n";
content += "light: " + postResponse.getLight() + "\n";
//textViewResult.setText(content);
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
get instance from preferences
sharedPreferences = getActivity().getSharedPreferences(preferences,
Activity.MODE_PRIVATE);
save to preferences
sharedPreferences.edit().putBoolean(key, value).apply();
get from preferences
sharedPreferences.getBoolean(key, defaultValue);
I'm trying to access SharedPreferences values in non-activity class
sharedPreferences = textViewResult.getContext().getSharedPreferences(preferences,
Activity.MODE_PRIVATE);
int redValue=sharedPreferences.getInt(RED_PROG,0);
...
If Context in not available in sendPref method then pass it to access SharedPreferences instance.
Use apply() instead of commit() if Api level is > 8
You can pass getContext() as parameter from fragment to non-activity class. Using the context you can get the shared preferences.
public static void sendPref(Context context) {
context.getSharedPreference.....
}

How I can passing data from one activity to multiple activities?

I want to send these data from current activity to more "BusInformationsCard" activity.
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int position) {
viewHolder.busLineName.setText(tickets.get(position).getBusLine());
viewHolder.seatsNumbers.setText(String.valueOf(tickets.get(position).getSeatNum()));
viewHolder.leavingTime.setText(tickets.get(position).getLeavingTime());
viewHolder.companyName.setText(tickets.get(position).getLeavingTime());
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here passing data to BusInformationCard
Intent ticketInfo = new Intent(mContext, BusInformationsCard.class);
ticketInfo.putExtra("busLine", tickets.get(position).getBusLine());
ticketInfo.putExtra("companyName", tickets.get(position).getCompany());
ticketInfo.putExtra("driverName", tickets.get(position).getName());
ticketInfo.putExtra("driverPhone", tickets.get(position).getDriverPhone());
ticketInfo.putExtra("seatNum", tickets.get(position).getSeatNum());
ticketInfo.putExtra("leavingTime", tickets.get(position).getLeavingTime());
ticketInfo.putExtra("latitude", tickets.get(position).getLatitude());
ticketInfo.putExtra("longitude", tickets.get(position).getLongitude());
mContext.startActivity(ticketInfo);
}
});
}
you can use shared preference to use your data in all over project. You just need to create an App Preference class like this:-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isUserLoggedOut(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("id_logged_in", true);
}
public static void setUserLoggedOut(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("id_logged_in", value);
mPrefsEditor.commit();
}
public static String getUserName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getString("userName", "");
}
public static void setUserName(Context ctx, String value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putString("userName", value);
mPrefsEditor.commit();
}
public static void clearAllPreferences(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.clear();
mPrefsEditor.commit();
}
}
and now just call these methods for save data and get saved data.
create a your own methods for save data and get saved data
You can get your data from one activity to another using Intent's getExtra method
Here is example ::
Example
String name;
name = getIntent().getStringExtra("driverName");
If you wish to pass the complete ticket object, you can use Serializable or Parcelable class in Java.
These classes help you to convert your object in a form which can be transferred between activities.
All you need to do in case of Serializable is to extend your ticket class
public class Ticket extends Serializable {}
In case of Parcelable, you need to add a little bit more code (in case of Java).
public class Ticket extends Parcelable {
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(busLine);
// Similarly for all the other parameters.
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Ticket createFromParcel(Parcel in) {
return new Ticket(in);
}
public Ticket[] newArray(int size) {
return new Ticket[size];
}
};
}
In both these cases, now you can directly pass your complete ticket object in the intent just like intent.putExtra("ticket", ticket); and can receive it in the other activity like, Ticket ticket = getIntent().getSerializableExtra("ticket") */ getParcelable */ if you have extended Parcelable.
The main difference between Parcelable and Serializable is the speed difference, Parcelable is faster than Serializable. Also, parcelable is customisable, and hence developers have the independence to play with their data.
Also Serializable used Java Reflection API, and hence ends up with a lot of garbage object during the conversion.

How to get value from Shared preference in Fragment?

I have been searching for the correct answer everywhere, but couldn't find it anywhere. That is why I am posting this question, this may look very similar to other questions but I didn't find the answer to this yet. I have to retrieve the user data that was saved during the login on Android device and I want to use the same data in a fragment, I tried using several answers found on StackOverflow, none of them worked for me. Look at the code below, how can I get the user values into strings?
SharedPreferences preferences = getActivity().getSharedPreferences("mysharedpref",Context.MODE_PRIVATE);
String user_name = preferences.getString("user_id",null);
String password = preferences.getString("role", null);
I have to pass these string values to a URL, but it doesn't work. I also checked passing values manually, it's working. For example, if I take assign values to the above strings like
String user_name="admin";
String password="administrator";
Best way to use your SharedPrefernce is by using your appContext that is accessible to the whole App(Common SharedPrefernce and accessible Everywhere).
Define your SharedPrefernce instance in your Application class with get and set methods as below : (If you have not created the Application class then create one as below, This class is called at the start of your app)
public class Application extends android.app.Application {
private static Application _instance;
private static SharedPreferences _preferences;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
/**
* Gets shared preferences.
*
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences() {
if (_preferences == null)
_preferences = PreferenceManager.getDefaultSharedPreferences(_instance);
return _preferences;
}
//set methods
public static void setPreferences(String key, String value) {
getSharedPreferences().edit().putString(key, value).commit();
}
public static void setPreferences(String key, long value) {
getSharedPreferences().edit().putLong(key, value).commit();
}
public static void setPreferences(String key, int value) {
getSharedPreferences().edit().putInt(key, value).commit();
}
public static void setPreferencesBoolean(String key, boolean value) {
getSharedPreferences().edit().putBoolean(key, value).commit();
}
//get methods
public static String getPrefranceData(String key) {
return getSharedPreferences().getString(key, "");
}
public static int getPrefranceDataInt(String key) {
return getSharedPreferences().getInt(key, 0);
}
public static boolean getPrefranceDataBoolean(String key) {
return getSharedPreferences().getBoolean(key, false);
}
public static long getPrefranceDataLong(String interval) {
return getSharedPreferences().getLong(interval, 0);
}
}
Declare the Application class in AndroidManifest.xml file with line android:name=".Application" as shown in below snippet:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Now, How to store key-value:
Application.setPreferences("Key","String_Value");
How to fetch key-value:
String value_string=Application.getPrefranceData("Key");
You can now set-SharedPrefernce key-value and get-SharedPrefernce value from anywhere in the app using public Application class and the static get and set methods
Firstly create a SharedPreference.java Class.
public class SharedPreference {
Context context;
SharedPreferences sharedPreferences;
String user_name;
String password;
public SharedPreference(Context co) {
context = co;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getPassword() {
password = getStringInput("password");
return password;
}
public void setPassword(String password) {
this.password = password;
stringInput("password", password);
}
public String getUser_name() {
user_name = getStringInput("Username");
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
stringInput("Username", user_name);
}
public void stringInput(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String getStringInput(String key) {
return sharedPreferences.getString(key, "0");
}
}
Now go into activity or Fragment
example: I'm gone use it in MainActivity.java
public class MainActivity extends AppCompatActivity {
Prefrences prefrences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
prefrences = new Prefrences(MainActivity.this);
prefrences.setUser_name("Rishabh Jain");
prefrences.setUser_name("8369554235");
Log.e("Details",prefrences.getUser_name()+" "+prefrences.getPassword())
}
}
The output will be Rishabh Jain 8369554235.
Similarly, you can use this in any Activity or any Fragment
I guess you are trying to get values with different key. Get values with same key you put them with.
String user_name = preferences.getString(preferences.KEY_USERNAME,null);
String password = preferences.getString(preferences.KEY_PASSWORD, null);
----BUT----
And don't use singleton pattern for SharedPreferences it is very bad to use Context in singleton. It will crash your app. You can figure it out why.
Instead use static methods.
public class PreferenceUtil {
public static final String PASSWORD = "PASSWORD";
public static void setInt(Context context, int in, String key) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
editor.putInt(key, in);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(key)) {
return settings.getInt(key, 0);
} else
return 0;
}
}
And access it like this
int password = PreferenceUtil.getInt(getActivity(), PreferenceUtil.PASSWORD);

How to use Shared Preferences in class to set all activities?

First of all: I searched for my question in StackOverflow.
Android - Using Shared Preferences in separate class?
And I get null expectation.
I am making a simple 2D game for Android Platform. I have to set only one level value for making this game. For making my game; I have created 3 activities. First activity; Takes the level number, and pass to the second one ( playground ). After that; İf gaming is passed, The second activity pass to the third. And When the user clicks to button level will be up ( +1 ). Level number is always 1 or 1 more than. I used to Shared Preference for saving my value but I does not work. How can I do it?
Here is my codes :
public class shared_level {
int level = 1;
private static Context context;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public final static String PREFS_NAME = "Level_preference_name";
public static void setInt( String key, int level) {
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, level);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
return prefs.getInt(key, 0 );
}
}
First actvitiy :
final shared_level shared_level =new shared_level();
Toast.makeText(this, "" + shared_level.getLevel(), Toast.LENGTH_SHORT).show();
pass_to_second.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent git = new Intent(getApplicationContext(), second.class);
git.putExtra("level" ,String.valueOf(shared_level.getLevel()) );
startActivity(git);
MainActivity.this.finish();
}
});
}
Second activity :
Bundle extras = getIntent().getExtras();
final String value = extras.getString("level");
Toast.makeText(this, "Level is : " + " " + value, Toast.LENGTH_SHORT).show();
sayı.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent git = new Intent(getApplicationContext(), third.class);
git.putExtra("level", String.valueOf(value));
startActivity(git);
second.this.finish();
}
});
Third's button activity goes to first :
Bundle extras = getIntent().getExtras();
final String value = extras.getString("level");
final shared_level shared_level =new shared_level();
int new_level =Integer.valueOf(value) + 1;
shared_level.setLevel(new_level);
Toast.makeText(this, "" + shared_level.getLevel(), Toast.LENGTH_SHORT).show();
sayım.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
third.this.finish();
}
});
You should pass context to shared_level class via the constructor.
public class shared_level {
private Context context;
public shared_level(Context context) {
this.context = context;
}
...
}
and create the instance of shared_level class like:
final shared_level shared_level = new shared_level(yourActivity.this);

android static methods usage

I am developing an android application, In which I created one "SessionManager.java" which contains only static methods, in splash screen Activity only, I am creating the instance for "SessionManager ", Because it is the
fist activity in app, But in sometimes, I am getting null object reference ,
is it necessary to instantiate Class in every activity ?
Sample code
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public static void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified!");
}
public static void setMobile (String login_mobile) {
editor.putString("mobile", login_mobile);
editor.commit();
}
public static String getMobile() {
return pref.getString("mobile", "00");
}
}
sometimes in some activities , getMobile() method is returning null value, why ? can I check null value before return that ? please give me any suggestions, I stuck here.
If you are using it for storing values in shared preference then do it like this
public class AppSharedPreferences {
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
private static AppSharedPreferences appSharedPrefrence;
public AppSharedPreferences(Context context) {
this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public AppSharedPreferences() {
}
public static AppSharedPreferences getsharedprefInstance(Context con) {
if (appSharedPrefrence == null)
appSharedPrefrence = new AppSharedPreferences(con);
return appSharedPrefrence;
}
public SharedPreferences getAppSharedPrefs() {
return appSharedPrefs;
}
public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
this.appSharedPrefs = appSharedPrefs;
}
public SharedPreferences.Editor getPrefsEditor() {
return prefsEditor;
}
public void Commit() {
prefsEditor.commit();
}
public void clearallSharedPrefernce() {
prefsEditor.clear();
prefsEditor.commit();
}
public void setUserId(String userid)
{
this.prefsEditor=appSharedPrefs.edit();
prefsEditor.putString("user_id", userid);
prefsEditor.apply();
}
public String getUserId() {
return appSharedPrefs.getString("user_id","");
}
}
and then to use it in class do it like this way
appSharedPreferences=AppSharedPreferences.getsharedprefInstance(ActivityLogin.this);
and then call your method using appsharedPreferences.yourMethod();

Categories

Resources