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

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);

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

SharedPreferences Across Multiple Activities Returns NULL

I have shared prefs to be used throughout my app but right now only four activities. The first activity is a recyclerview with checkboxes and the checked status is saved (in the recycler adapter) for each checkbox using a shared prefs helper class. The next activity is then launched as a tablayout with fragments containing a list of random items.
When the user clicks any of these items in the second activity's fragment, a third activity is launched. Here, I try to retrieve the values from the shared prefs helper class but it returns null, same situation in fourth activity too. Also, when I back press twice to first activity, it also returns null.
I would post my code for all activities but that would just make the question lengthy. Here's my helper class:
public class WalpyPrefsHelper {
public Context context;
public SharedPreferences customizePrefs, tabsCountPrefs;
public SharedPreferences.Editor editor, tabsEditor;
public static final String CUSTOMIZE_TABS_PREFS = "customizeTabsPrefs";
public static final String COUNT_TABS_PREFS = "countTabsPrefs";
public static final String KEY_NATURE = "nature";
public static final String KEY_SPACE = "space";
public static final String KEY_SEASONS = "seasons";
public static final String KEY_ART = "art";
public static final String KEY_SCIFI = "sci_fi";
public static final String KEY_MISC = "misc";
public static final String KEY_COUNT = "count_tabs";
public WalpyPrefsHelper(Context context) {
this.context = context;
customizePrefs = context.getSharedPreferences(CUSTOMIZE_TABS_PREFS, Context.MODE_PRIVATE);
editor = customizePrefs.edit();
tabsCountPrefs = context.getSharedPreferences(COUNT_TABS_PREFS, Context.MODE_PRIVATE);
tabsEditor = tabsCountPrefs.edit();
}
public void saveNaturePrefs(String s){
editor.putString(KEY_NATURE, s).apply();
}
public String getKeyNature(){
return customizePrefs.getString(KEY_NATURE, null);
}
public void removeNaturePrefs(){
editor.remove(KEY_NATURE).apply();
}
public void saveSpacePrefs(String s){
editor.putString(KEY_SPACE, s).apply();
}
public String getKeySpace(){
return customizePrefs.getString(KEY_SPACE, null);
}
public void removeSpacePrefs(){
editor.remove(KEY_SPACE).apply();
}
public void saveSeasonsPrefs(String s){
editor.putString(KEY_SEASONS, s).apply();
}
public String getKeySeasons(){
return customizePrefs.getString(KEY_SEASONS, null);
}
public void removeSeasonPrefs(){
editor.remove(KEY_SEASONS).apply();
}
public void saveArtPrefs(String s){
editor.putString(KEY_ART, s).apply();
}
public String getKeyArt(){
return customizePrefs.getString(KEY_ART, null);
}
public void removeArtPrefs(){
editor.remove(KEY_ART).apply();
}
public void saveSci_FiPrefs(String s){
editor.putString(KEY_SCIFI, s).apply();
}
public String getKeyScifi(){
return customizePrefs.getString(KEY_SCIFI, null);
}
public void removeSci_FiPrefs(){
editor.remove(KEY_SCIFI).apply();
}
public void saveMiscPrefs(String s){
editor.putString(KEY_MISC, s).apply();
}
public String getKeyMisc(){
return customizePrefs.getString(KEY_MISC, null);
}
public void removeMiscPrefs(){
editor.remove(KEY_MISC).apply();
}
public void removeAllPrefs(){
editor.remove(KEY_NATURE).apply();
editor.remove(KEY_SPACE).apply();
editor.remove(KEY_SEASONS).apply();
editor.remove(KEY_ART).apply();
editor.remove(KEY_SCIFI).apply();
editor.remove(KEY_MISC).apply();
}
public void saveCount(int count) {
tabsEditor.putInt(KEY_COUNT, count).apply();
}
public int getSaveCount(){
return tabsCountPrefs.getInt(KEY_COUNT, 0);
}
}
The preferences are saved in first activity recycler adapter like below snippet:
viewholder.customizeSelImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nature, space, seasons, art, scifi, misc;
switch (position) {
case 0:
nature = prefsHelper.getKeyNature();
if (viewholder.customiseCheckBox.isChecked()) {
viewholder.customiseCheckBox.setChecked(false);
viewholder.customiseCheckBox.setVisibility(View.INVISIBLE);
if (nature != null) {
prefsHelper.removeNaturePrefs(); // infer nullity
if (count > 0) {
count--;
Log.d(TAG, "Count Value:\t" + count);
}
Log.d(TAG, "Position:\t" + position + " is UNChecked");
}
} else {
viewholder.customiseCheckBox.setChecked(true);
viewholder.customiseCheckBox.setVisibility(View.VISIBLE);
count ++;
Log.d(TAG, "Count Value:\t" + count);
prefsHelper.saveNaturePrefs(Constants.NATURE); // save value. Works fine
Log.d(TAG, "Position:\t" + position + " is Checked");
}
break;
In next activity, I am able to retrieve the shared prefs values like below snippet:
String space = prefsHelper.getKeySpace();
String nature = prefsHelper.getKeyNature();
String seasons = prefsHelper.getKeySeasons();
String art = prefsHelper.getKeyArt();
String scifi = prefsHelper.getKeyScifi();
String misc = prefsHelper.getKeyMisc();
after initializing like this: prefsHelper = new WalpyPrefsHelper(this); but in third and fourth activities, those strings above return null values.
----Edited Part---
Second Activity Where Prefs Are Used:
public void setUpTabs() {
prefsHelper = new WalpyPrefsHelper(this);
int count = prefsHelper.getSaveCount();
Log.d(TAG, "Tabs Count:\t" + count);
setUpViewPager(viewPager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
space = prefsHelper.getKeySpace();
nature = prefsHelper.getKeyNature();
seasons = prefsHelper.getKeySeasons();
art = prefsHelper.getKeyArt();
scifi = prefsHelper.getKeyScifi();
misc = prefsHelper.getKeyMisc();
pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this);
pagerAdapter.addTab(new Top30Fragment(), Constants.Top30);
if (nature != null) {
pagerAdapter.addTab(new NatureFragment(), Constants.NATURE);
}
if(space != null){
pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
}
if (seasons != null){
pagerAdapter.addTab(new SeasonsFragment(), Constants.SEASONS);
}
if (art != null){
pagerAdapter.addTab(new ArtFragment(), Constants.ART);
}
if (scifi != null){
pagerAdapter.addTab(new SciFiFragment(), Constants.SCI_FI);
}
if (misc != null){
pagerAdapter.addTab(new MiscFragment(), Constants.MISC);
}
pagerAdapter.addTabAtLastPosition(new PrefsFragment(), Constants.PREFS);
viewPager.setAdapter(pagerAdapter);
}
I have used shared prefs to set the tablayout at app install time but after navigating other activities and back to this, those tabs from prefs are removed, in other scenarios, my last tab then contains the view and data of the nature fragment from prefs.
In adapter and last two activities in sequence, I am getting the key like this but it returns null:
prefsHelper = new WalpyPrefsHelper(this);
Log.d(TAG, "Nature Key:\t" + prefsHelper.getKeyNature());
Also, in the adapter, the value returns null and in other subsequent activities after the second activity. Is this sharedprefs behavior, I have misconfigured somewhere or sharedprefs can't be passed from activity to fragment and adapter context?
I have tried .apply() and .commit() for the editor but same situation occurs.
Anyone understands why? Thanks.
I have fixed this problem by using sqlite to persist and retrieve the values.
Looking at the attached code flow, I could not find any problematic parts. Although each activity has a preference manager class instance created and used, the SharedPrefenrece object itself is shared as one object, so that is not a problem.
Please check again whether the preference value is deleted or not in the flow.
Also, if you attach the part that uses prefsHelper in each activity, troubleshooting will be helpful.

Get value from one activity to another one

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.

Static Value Android Studio

I have two Activities. And a static integer called as counter.
So if I press a button in activity 'A' then counter = counter + 1.
Here is the code from activity a:
public static int counter = 0;
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
if (counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
And here it is from activity b :
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.counter = a.counter + 1;
if (a.counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
My problem is when i tried to press a button from activity a 3 times it work perfectly. So the values are 3 now.
But when i tried press a button from activity b, the value is going restart into 0. Actually i didn't destroy activity a.
So what i want is the value is going continouosly even i press from activity a or b.
Any ideas ?
Edited :
I have edit the code. Tagihan activity is what im trying to accomplished. So when the counter is 5, then tagihan activity is changing.
Dont use static data, this is a bad approach and is not a common OOP-way to develope, instead try passing data between activities...
Act1
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
Act2:
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Android development web is giving an introduction to this:
http://developer.android.com/training/basics/firstapp/starting-activity.html
After your edit, I can see that you need a "global varfiable" that can be read/write for all the activities:
Solution:
All activities are embedded in an Application, so if you habe fields/members in the application you can access to them with a stadard setter/getter
you need:
Define an application
public class MyApplication extends Application {
private int counterVariable;
public int counterVariable() {
return this.counterVariable;
}
public void setCounterVariable(int someVariable) {
this.counterVariable = someVariable;
}
}
add the App to the manifest:
<application
android:name="MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Then in your activities get and set the variable like so:
// cast to Application and call the setter
((MyApplication) this.getApplication()).counterVariable(1);
// cast to Application and call the getter
int counter = ((MyApplication) this.getApplication()).getCounterVariable ();
Please use the below code:
// Generalized form of Avoiding the Static value holding:
public class SPDataHandler {
private Context mContext;
private SharedPreferences mPreference;
public SPDataHandler(Context context) {
this.mContext = context;
this.mPreference = mContext.getSharedPreferences("SAMPLE_SP", Context.MODE_PRIVATE);
}
/**
* COMMON SETTER FOR INTEGER DATA
*/
private void setIntegerData(String key, int value) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* COMMON GETTER FOR INTEGER SP DATA
*/
private int getIntegerSpData(String key, int defaultValue) {
return this.mPreference.getInt(key, defaultValue);
}
// Your Getter and Setter
public int getmCount() {
return this.getIntegerSpData("Count", 1);
}
public void setmCount(int cont) {
this.setIntegerData("Count", cont);
}
}
// Your Activity A
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
// Your Activity B
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}

Using SharedPreferences across multiple classes?

I have a SharedPreferences that currently works in one class but doesn't work in a second class. I think I might be calling it wrong, because the error I get says:
The method getSharedPreferences(String, int) is undefined for the type CheckPreferences
The code that works correctly with the SharedPrefernces is this:
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
//String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
//prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
{
public void onSettingsSaved()
{
// This function let's the activity know that the user has saved their preferences and
// that the rest of the app should be now be shown.
check.saveSettings();
}
public void onCancel()
{
Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
}
});
cp.show();
}
In my other class, I don't know if I'm just calling it incorrectly or if I'm looking at it completely incorrectly. The class is shown below:
package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.CheckBox;
public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference;
String userLatitudePreference;
String userLongitudePreference;
String userVelocityPreference;
String userAltitudeChoice;
String userLatitudeChoice;
String userLongitudeChoice;
String userVelocityChoice;
public interface CheckPreferencesListener
{
public void onSettingsSaved();
public void onCancel();
}
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId())
{
case R.id.saveBtn:
{
saveSettings();
listener.onSettingsSaved();
dismiss();
break;
}
case R.id.cancelBtn:
{
listener.onCancel();
dismiss();
break;
}
}
}
};
// Save Button
this.findViewById(R.id.saveBtn).setOnClickListener(click);
// Cancel Button
this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}
public void saveSettings()
{
// This function is called when the user chooses the save their preferences
if (altitudeCheckBox.isChecked())
{
userAltitudeChoice = "true";
prefEditor.putString(userAltitudePreference, userAltitudeChoice);
prefEditor.commit();
}
else if (latitudeCheckbox.isChecked())
{
userLatitudeChoice = "true";
prefEditor.putString(userLatitudePreference, userLatitudeChoice);
prefEditor.commit();
}
else if (longitudeCheckbox.isChecked())
{
userLongitudeChoice = "true";
prefEditor.putString(userLongitudePreference, userLongitudeChoice);
prefEditor.commit();
}
else if (velocityCheckbox.isChecked())
{
userVelocityChoice = "true";
prefEditor.putString(userVelocityPreference, userVelocityChoice);
prefEditor.commit();
}
else
{
}
}
}
The error I mentioned above occurs on this line:
pref = getSharedPreferences("shared_prefs", 1);
Any help will be greatly appreciated. I'd love to know what I'm doing wrong.
Ofcourse SharedPreferences is same across multiple classes. It allows you to save and retrieve persistent key-value pairs of primitive data types in your application.
Standard practice is to have one single Helper class with all static methods to save and retrieve key-value pairs of each type. Also, have all your keys in one static class SharedPreferenceKeys. It avoids silly typographical mistakes. Following is sample class which you can use:
package com.mobisys.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class HelperSharedPreferences {
public static class SharedPreferencesKeys{
public static final String key1="key1";
public static final String key2="key2";
}
public static void putSharedPreferencesInt(Context context, String key, int value){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putInt(key, value);
edit.commit();
}
public static void putSharedPreferencesBoolean(Context context, String key, boolean val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putBoolean(key, val);
edit.commit();
}
public static void putSharedPreferencesString(Context context, String key, String val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putString(key, val);
edit.commit();
}
public static void putSharedPreferencesFloat(Context context, String key, float val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putFloat(key, val);
edit.commit();
}
public static void putSharedPreferencesLong(Context context, String key, long val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putLong(key, val);
edit.commit();
}
public static long getSharedPreferencesLong(Context context, String key, long _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getLong(key, _default);
}
public static float getSharedPreferencesFloat(Context context, String key, float _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getFloat(key, _default);
}
public static String getSharedPreferencesString(Context context, String key, String _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, _default);
}
public static int getSharedPreferencesInt(Context context, String key, int _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, _default);
}
public static boolean getSharedPreferencesBoolean(Context context, String key, boolean _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, _default);
}
}
To put value (say boolean), call following from activity:
HelperSharedPreferences.putSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
To get same value, call following:
HelperSharedPreferences.getSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
Last value is default value.
You should have to call this method via context reference variable.
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc=context;
...
pref = shc.getSharedPreferences("shared_prefs", 1);
...
}
The Dialog class doesn't have a getSharedPreferences method defined. You probably want:
getContext().getSharedPreferences(...)

Categories

Resources