Android - Shared Preferences won't load my options - android

I have four buttons(ImageView) inside a popup window, each button will change the the color of a button in my service class to the desired color. When I click one of these buttons it will change the color but when I exit from the app en start it again, my option is not saved.
//Inner class inside my MainActivity
public static class SetReng {
static int reng;
public SetReng() {
}
public int getReng() {
return this.reng;
}
}
public void onGreen (View view) {
SetReng.reng = Color.GREEN;
ImageView Green = (ImageView)view.findViewById(R.id.kesk);
Green.setPressed(true);
Toast.makeText(MainActivity.this, "Bloq color set to green", Toast.LENGTH_SHORT).show();
editor.putInt("Which", SetReng.reng);
editor.apply();
}
Here's the code in my service that should load the color options
SetReng putReng = new SetReng();
int theReng= putReng.getReng();
SharedP= PreferenceManager.getDefaultSharedPreferences(context);
int colorOp= SharedP.getInt("Which", theReng);
mButtondeh= new Button(this);
mButtondeh.setBackgroundColor(colorOp);
What am I doing wrong?
I'm stuck with this for the last couple of days so anything will be appreciated!

Try using
...
editor.putInt("Which", SetReng.reng);
editor.commit(); // instead of apply
...

I solved it by replacing getReference() manager with getSharedPreference() and in my service, I changed PreferenceManager.getDefaultSharedPreferences(context); to SharedP = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); And now it works perfectly!

Related

Programatically make LinearLayout dismissible in android studio using shared preference

There is this thing I want to achieve, I have searched all questions on SO and no answer related to this, so I guess no one has asked which makes me curious.
On my XML, Android studio app, I added a Linear Layout, under the Linear layout, I added a 《TextView with text "Dismiss"》.
I want to set an onclick listener to this textview, once user clicks this TextView with text "Dismiss" I don't want that user to see that Linear Layout again on the page until they reinstall the app.
Logically, the Linear Layout will be like a notice to highlight something on my app when users arrive at that page, but instead of that notice to stay there forever I want user to be able to dismiss it which shows they have gotten the notice.
My workings:
Since I want each app user to decide not to see that text again after clicking dismiss, I need to use shared preference on that TextView with text "Dismiss", so whenever app gets the value of this shared preference then it will hide that layout.
I can set the LinearLayout to be invisible if that value from shared preference is found when stored on the app
The question now, how will I set this shared preference and which code will I use to make the Layout "GONE" or "INVISIBLE" if the TextView with text "Dismiss" is clicked?
Your intelligent solution to this will be much appreciated.
check this out , its in Java, and this will hide the layout after clicking the dismisstextview and when u re open it alert will still be hidden.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getSharedPreferences(getApplicationContext().getPackageName(),0);
editor = sharedPref.edit();
LinearLayout alertLayout = (LinearLayout)findViewById(R.id.alertLayout);
TextView textViewDismiss = (TextView)findViewById(R.id.textViewDismiss);
if(sharedPref.getBoolean("isLayoutAlertShown",false)){
alertLayout.setVisibility(View.GONE);
}else{
alertLayout.setVisibility(View.VISIBLE);
}
textViewDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertLayout.setVisibility(View.GONE);
editor.putBoolean("isLayoutAlertShown",true);
editor.apply();
}
});
}
}
I would recommend you to use SharedPreferences since this is related to setting matter. You can refer to this link: https://developer.android.com/training/data-storage/shared-preferences#java
You have to call this method at the onCreate. So it will check if the there is showLayout stated true or false, then it will update the design.
//Inside onCreate
private void initSharedPreference(final Activity activity, final LinearLayout linearLayout) {
final SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.getBoolean("showLayout", false)) {
linearLayout.setVisibility(View.GONE);
} else {
linearLayout.setVisibility(View.VISIBLE);
}
}
At the setOnClickListener you need to implement this method.
//At the button
private void setSharedPrefShowLayout(final Activity activity, final Boolean isVisible) {
final SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("showLayout", isVisible);
editor.apply();
}

pick a color from the holocolorpicker then saved using shared preferences

am trying to save he color picked from the holocolorpicker and use it in another activity
before the onCreate method in the settings activity i put this lines
private String SettingsTAG0 = "backcolorValue";
private SharedPreferences backcolorprefs;
private static int backcolorValue = 0;
after the onCreate method in the settings activity i put this lines
public void onColorChanged(int color) {
ColorPicker picker0 = (ColorPicker) findViewById(R.id.backpicker);
backcolorValue = picker0.getColor();
Editor editor0 = backcolorprefs.edit();
editor0.clear();
editor0.putInt("back_colorcode", backcolorValue);
editor0.commit();
}
before the onCreate method of the other activity i put this lines
private String SettingsTAG0 = "backcolorValue";
private SharedPreferences backcolorprefs;
private static int backcolorValue = 0;
in the onCreate method of the other activity i put this lines
backcolorprefs = getSharedPreferences(SettingsTAG0, 0);
backcolorprefs.getInt("back_colorcode", backcolorValue);
View view = this.getWindow().getDecorView();
view.setBackgroundColor(backcolorValue);
i am a super newbie to android and java but i make a try but nothing is happened
any help please
This is how sharedpreference used:
// put int
SharedPreferences sharedpreferences = getSharedPreferences("MyPreference", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("back_colorcode", backcolorValue);
editor.commit();
// get int
SharedPreferences sharedpreferences = getSharedPreferences("MyPreference", Context.MODE_PRIVATE);
int backcolorValue = sharedpreferences.getInt("back_colorcode", 0)
Nothing happened because you are not assigning value read from preferences to backcolorValue. This line:
backcolorprefs.getInt("back_colorcode", backcolorValue);
simply reads it and DOESN'T store in backcolorValue. Do:
backcolorValue = backcolorprefs.getInt("back_colorcode", backcolorValue);
Also, in onColorChanged, I don't see that you're initialising backcolorprefs, so make sure you do. Btw, for getSharedPreferences, you should use constant Context.MODE_PRIVATE, instead of hardcoded value of 0.
onColorChanged method parameter is color code selected from ColorPicker. save same in SharedPreferences :
public void onColorChanged(int color) {
Editor editor0 = backcolorprefs.edit();
editor0.clear();
editor0.putInt("back_colorcode", color);
editor0.commit();
}
In second Activity get color code from preference and pass to setBackgroundColor :
int colorCode=backcolorprefs.getInt("back_colorcode", Color.BLACK);
View view = this.getWindow().getDecorView();
view.setBackgroundColor(colorCode);

Cant use SavePreferences for TextView

I have a TextView. When the Activity is first created the Value of the textView is "", as in nothing. But the user can initiate some actions that can make the text="st". That works fine, once more that works fine. The problem is when I leave the page and come back instead of text="st" , it's " " as in nothing. So the user has to waste time and get the textView back to "st" through some actions.
I tried to save the TextView using SavePreferences but since the value of TextView is nothing when the activity starts SavePreferences does exactly what it's supposed to do and makes the TextView equal nothing. Isn't there some way for me to save the value of the TextView. I have other Views on my page I do not want to save, so how do I save just the TextView as it is when the user leaves the app or activity?
TextView s1;
s1 = (TextView)findViewById(R.id.s1);
//9 miles down the page
LoadPreferences();
SavePreferences("MEM46", s1.getText().toString());
LoadPreferences();}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem46 = sharedPreferences.getString("MEM46", "");
s1.setText(strSavedMem46);
lay1.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(xxx.this);
alert.setTitle("Help"); //Set Alert dialog title here
alert.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int choice){
if(choice == 0) {
d.cancel();
}
else if(choice == 1){
TextView ss1=(TextView)findViewById(R.id.s1);
ss1.setText("st");d.cancel(); }
else if(choice == 2) {
TextView ss1=(TextView)findViewById(R.id.s1);
ss1.setText("");d.cancel();}});
alert.show();
return true;
}});
At which point exactly do you call LoadPreferences/SavePreferences?
Saving should happen only when the user leaves the activity, so onPause() must be overriden to call the savePreference(). Loading should be done in onStart().

ADK - Unable to find layout using R.id.x

I am attempting to change the background color of my Android app (I'm new to the ADK).
I read in another question that I would have to use another LinearLayout between my main layout (RelativeLayout) and all of the other views in the app, and change the color of that instead. I want a preference to dictate which color the background changes to, and the preference activity and everything is running smoothly; however, when I pass R.id.bg (bg is the LinearLayout's ID) to findViewById(), it returns null and throws an NPE whenever I attempt to change the background color.
EDIT: Y'know what, here's the entire class's source. :P
public class Preferences extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
private void showToast(CharSequence text) {
Context context = getApplicationContext();
showToast(context, text, 3000);
}
private void showToast(Context context, CharSequence text, int duration) {
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equalsIgnoreCase("list_color")) {
LinearLayout bg = (LinearLayout) findViewById(R.id.bg);
String color = sharedPreferences.getString("list_color", "White");
if (bg == null) {
showToast("Unable to change background color");
} else {
if (color.equals("White")) {
bg.setBackgroundColor(android.R.color.white);
showToast("Background color set to white");
} else if (color.equals("Black")) {
bg.setBackgroundColor(android.R.color.black);
showToast("Background color set to black");
}
} // end NP test
}
}
}
You cannot fetch a View directly from preferences in the traditional manner.
The closest you can do is get the Preference using findPreference():
Preference myPreference = findPreference("key");
If you need the View (which I assume you do), you can try this:
View v = myPreference.getView(null, null);
And that should return the View container which represents the Preference.
Show your onCreate method.
Maybe you forget to add setContentView(R.layout.your_layout);:
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
or import incorrect R file.

How can I use another Color Picker without preferenceActivity?

I have a color picker which I use in sharedPrefereces. With the default colorpicker I managed to acheive what I want, but I noticed there is no black or white colors. http://www.yougli.net/android/a-photoshop-like-color-picker-for-your-android-application/
I would like to use this code but in the last rows, he shows an example, where I can see it is attached to a preferenced Screen. Instead of it I use my own activity with buttons where using shared Preferences I can save datas/values (so its not a preferenceActivity, just an Activity). For example clicking on a layout results:
OptVertexColor = (LinearLayout) findViewById(R.id.OptVC);
OptVertexColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadChartVertexColor();
ColorPickerDialog dlg = new ColorPickerDialog(settings.this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
SaveChartVertexColor("vertexcolor", color);
}
}, loadedVertexColor);
dlg.setTitle("Select new color");
dlg.show();
}
});
The default color picker dialog appears and I can save a color. Now how can I use this without a preference screen and acheive the same thing? I tried to copy the code above to this code, but I coudnt figure out how to handle it.
public class MySettings extends PreferenceActivity implements OnPreferenceClickListener, ColorPickerDialog.OnColorChangedListener {
public boolean onPreferenceClick(Preference pref)
{
new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();
return true;
}
public void colorChanged(String key, int color)
{
((PreferenceScreen)this.findPreference(SETTINGS_KEY)).getEditor().putInt(key, color).commit();
}
}
Thank you in advance!
In your own Activity, add
implements ColorPickerDialog.OnColorChangedListener
to the class declaration.
Add to your class body:
public void colorChanged(String key, int color) {
//create your SharedPreferences and your SharedPreferences.Editor here
editor.putInt(key, color);
editor.commit();
}
And in a button click listener add:
new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();
This should work. Let me know if you I failed to answer your question, and I'll see what I can do.

Categories

Resources