Android - Display button with sharedpreference value - android

I'm currently working in an Activity which saves text from Button1...button8.
But it not display text of button.i don't understand.
MainActivity=>
public void getName(){
SharedPreferences preferences = getSharedPreferences("sample",0);
int a=(preferences.getInt("num",0));
String ab=(preferences.getString("Name",""));
if(a==0){
button1.setVisibility(View.GONE);
button1.setVisibility(View.VISIBLE);
button1.setText(ab);
}
if(a==1){
button2.setVisibility(View.GONE);
button2.setVisibility(View.VISIBLE);
button2.setText(ab);
}
if(a==3){
button3.setVisibility(View.GONE);
button3.setVisibility(View.VISIBLE);
button3.setText(ab);
}
}
SetupActivity=>
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("Sample", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name", editText.getText().toString());
editor.putInt("num", myNum);
editor.commit();
Intent intent = new Intent(Setup.this, MainActivity.class);
startActivity(intent);
}

Check your Preference Names, you are using
getSharedPreferences("Sample", 0);
and
getSharedPreferences("sample",0);

not display text of button
That because (preferences.getString("Name","") return " " as default and this is probably the case.
In addition the lines:
button_.setVisibility(View.GONE);
button_.setVisibility(View.VISIBLE);
is really not make sense. you can drop the line:
button_.setVisibility(View.GONE);

First remove this line from the getName method
button_.setVisibility(View.GONE);
Then check out the KEY you are using to save the name of buttons in your case You are saving with the name of Sample and retrieving it as sample. Keep it mind key is case sensitive.
Now coming to other point in case you wrote key "Sample" just to demonstrate us the question. Before starting I would like to ask you where are you calling your method getName in mainActivity. But anyways here are the secure way of doing this:
When saving your button names add these lines
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("Sample", 0);
SharedPreferences.Editor editor = preferences.edit();
if(editText.getText().toString().length()>0){
editor.putString("Name", editText.getText().toString());
editor.putInt("num", myNum);
editor.commit();
Intent intent = new Intent(Setup.this, MainActivity.class);
startActivity(intent);}
}
and in getName method just do this
public void getName(){
SharedPreferences preferences = getSharedPreferences("sample",0);
int a=(preferences.getInt("num",0));
String ab=(preferences.getString("Name",""));
if(a==0){
button1.setVisibility(View.VISIBLE);
button1.setText(ab);
}
if(a==1){
button2.setVisibility(View.VISIBLE);
button2.setText(ab);
}
if(a==3){
button3.setVisibility(View.VISIBLE);
button3.setText(ab);
}
}

Related

Skip past Android Activity if it was already seen [duplicate]

I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}

last seen activity not save in shared preferences

in first activity i have 3 button firs button go to subject list , second button show last seen activity
Im use this for last seen activity :
in subject list for each item save number in shared preferences and when user click on last seen number in subject list call and show last activity
this code work well but when i turn of phone or app not open for minutes last seen show nothing why?
please help me
in subject list class
shared = getSharedPreferences("count", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
public static int counter;
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent0 = new Intent(getApplicationContext(),Study.class);
startActivity(intent0);
counter=1;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
}
if (i == 1) {
counter=2;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent1 = new Intent(getApplicationContext(),Mo.class);
startActivity(intent1);
}
if (i == 2) {
counter=3;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent2 = new Intent(getApplicationContext(),Sa.class);
startActivity(intent2);
}
in fist activity that contain last seen button :
case R.id.last_seen_btn:
if (SubjectActivity.counter==0){
Toast.makeText(getApplicationContext(), " nothing",
Toast.LENGTH_LONG).show();
}
if (SubjectActivity.counter==1){
Intent intent = new Intent(getApplicationContext(),Study.class);
startActivity(intent);
}
if (SubjectActivity.counter==2){
Intent intent = new Intent(getApplicationContext(),Mo.class);
startActivity(intent);
}
if (SubjectActivity.counter==3){
Intent intent = new Intent(getApplicationContext(),Sa.class);
startActivity(intent);
}
You shall use always the "application preferences" and best is to access them via the Application object. There is caching on SharedPreferences aand it's creating some issues some time.
Also update always the SharedPreferences before opening the Activity (if i == 0)
public class MyApp extends Application {
private SharedPreferences mMyPref;
#Override
public void onCreate() {
super.onCreate();
mMyPref = getSharedPreferences("my_pref_name", MODE_PRIVATE);
}
public SharedPreferences getMySharedPreferences(){
return mMyPref;
}
}
In your parts of code where you want to read/write just use
((MyApp)getApplicationContext()).getMySharedPreferences() ....
of of course create a local variable that gives you the possibility to work with it.

SharedPreferences Fragment not work

I try call SharedPreferences, and I pass a parameters but not work (not update and not put data)
I don't know I do wrong?
public void put(String value){
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
editor.putString("isFirstRunCheck", value);
editor.commit();
}
public void checkFirstRun3(){
SharedPreferences prefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
String name ="";
if (restoredText != null) {
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
}
if(name.equals("true")){
Toast.makeText(getActivity(), "click si ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "click no ", Toast.LENGTH_SHORT).show();
}
}
I put my "put()" I do not see it work
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
cbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
}
});
I'm not sure why you don't think this is working, but I'm guessing it is because your code doesn't do what you think it does.
First of all, the comment on this line is wrong:
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
The second parameter to getString() is the default value- in this case you are specify that the default value should be an empty string if you have not previously saved a value to the "isFirstRunCheck" key.
Second, you seem to be expecting a value of "si". However, you are only ever calling put("true") and put("false")- you never call put("si"), so your conditional in checkFirstRun3() will always be false.
As an aside, a String is an odd way to save boolean data. SharedPreferences has a getBoolean() and a putBoolean() that will likely suit your needs better.
Try to change
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
to
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor spe = sp.edit();
Use
spe.putString("yourStringKey", yourStringValue).commit()
and then get your data using the "yourStringKey"
and don't forget to call your put(someData) method.

Delete data from shared preferences in android

I am trying to delete the data from shared preferences. But I cant do that. To track that the data is removed or not, I am using this code:
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();
getApplicationContext().getSharedPreferences(share_pref_file, 0).edit().clear().commit();
String strJson = prefs.getString("jsondata","");
if(strJson != null)
{
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
But in logcat window it is showing me "cccccccccccccccccccccccccccc" value every time.
So can anyone help me out that how to remove/delete the data from shared preferences so that if I click on 'logout' button it will remove all the stored data? Thanks in advance.
An empty string is still a string (and String("") != null will return true). Try this instead:
if(!strJson.equals(""))
This assumes the empty string will never be a valid input in your SharedPreferences in the first place.
Try this one inside the button click event to clear the SharedPreferences values.
Editor editor = getSharedPreferences("MyPref", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Try editor.clear(); followed by a editor.commit();
Here is one example that I've used:
Preference clearPref = (Preference) findPreference("MyPref");
btnLogout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Toast.makeText(getBaseContext(), "All data cleared!", Toast.LENGTH_SHORT).show();
return true;
}
});
Either change this:
String strJson = prefs.getString("jsondata", "");
To:
String strJson = prefs.getString("jsondata", null);
And then check:
if(strJson != null) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
Or keep it as it is and check it like this:
if(strJson.equals("")) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
settings.edit().clear().commit();
is a one line code I am using, works perfectly
It is my solution:
You can put null instead of your favorite data in shareprefrences
getApplicationContext();
SharedPreferences.Editor pref = (Editor) getSharedPreferences("data", MODE_PRIVATE).edit();
pref.putString("admin_no", null);
pref.commit();

How to save the state of the toogleButton on/off selection?

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".
So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .
Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck

Categories

Resources