I am new in Android, and got a task to develop a small project to submit in my college, i have tried my best but now i need some help
Let me tell you first, what i am trying to do ?
I have two Activities, MainActivity and AccountActivity
In MainActivity i am using button to switch to AccountActivity
In AccountActivity i am trying to store strBalance value in SharedPreference but whenever i do click on back button and then again come to AccountActivity always getting "1000" not that value which i have stored in SharedPreference.
Here is the complete code of AccountActivity.java:-
public class AccountActivity extends Activity {
EditText editAmount;
int strAmount;
Button btnPayment;
TextView textBalance;
int strBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
editAmount = (EditText) findViewById(R.id.editAmt);
btnPayment = (Button) findViewById(R.id.btnPay);
textBalance = (TextView) findViewById(R.id.textBalance);
strBalance = 1000;
textBalance.setText("Your current balance is: $ "+strBalance);
btnPayment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input
if(strAmount>strBalance) {
Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
}
else
{
strBalance = strBalance - strAmount; // 1000 - 500 = 500
textBalance.setText("Your current balance is: $ "+strBalance);
Log.v("strBalance", String.valueOf(strBalance)); // 500
editor.putInt("key_balance", strBalance);
editor.commit();
}
}
});
}
}
Do this,
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
int any_variable = sharedPreferences.getInt("key_balance", 0);
Remove initialisation and do this in your onCreate and then use the new variable as you strBalance.
-Check Both the preference and key name are same or not.
You did not retrieve data from SharedPreferences
Write your code in onResume() like this:
#Override
protected void onResume() {
super.onResume();
// SharedPreferences retrieval code
}
To know more about SharedPreferences check this link.
This should work fine:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
strBalance = pref.getInt("key_balance",1000);
} else {
strBalance = 1000;
}
Instead of
strBalance = 1000;
Related
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?
Here is the xml file (only the button part):
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Catch"
android:id="#+id/button"
android:onClick="toggleCatch" />
And here is toggleCatch:
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
}
What could I do to make it work?
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference
and then when you create the activity you set the state of the btn based on the data you loaded.
if you do it just for practice, I believe that the sharepreference will be just fine.
https://developer.android.com/training/data-storage/shared-preferences
to store any data locally in the sharedPreference:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
to get the saved data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..
hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.
To achieve that in your code sample
public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(BUTTON_STATUS, isCaught);
editor.apply();
}
And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
isCaught = prefs.getBoolean(BUTTON_STATUS, false);
if (isCaught) {
button.setText("Release");
} else {
button.setText("Catch");
}
}
Here is my code it is working please tell me code button for "no thanks" if user tap on this button then dialog box never show at all
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid,url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id,version,ver;
ImageView mega4,todayTips,latstnews,sportquiz,tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+"since you have already used it %totalLaunchCount% times! "
+"It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
Here is my code actually i want to implement app rating dialog box in application that should display once in three day
You have to initialize your SharedPreferences and Editor Object like this:
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
UPDATE
Just save a boolean when user cliks on no thanks and check it before showing the dialog. If it true then it will not show the dialog box.
//Saving a boolean on no thanks button click
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true));
editor.apply();
Access it in your dialog showing method.
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
if (prefs.getBoolean("NO THANKS", false)) {
return;
}else {
SharedPreferences.Editor editor = prefs.edit();
//YOUR CODE TO SHOW DIALOG
editor.apply();
}
FULL CODE
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid, url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id, version, ver;
ImageView mega4, todayTips, latstnews, sportquiz, tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
if (sharedPrefs.getBoolean("NO THANKS", false)) {
return;
} else {
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
//YOUR CODE TO SHOW DIALOG
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
prefsEditor.apply();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
//Saving a boolean on no thanks button click
SharedPreferences prefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true);
editor.apply();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+ "since you have already used it %totalLaunchCount% times! "
+ "It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
here is my code as a function for 10 days.
I made the initial value current time - 11 days to make sure it will run first time app launches
public void dialogEvery10Days() {
Long duration = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getLong("duration", System.currentTimeMillis()-TimeUnit.DAYS.toMillis(11));
if (System.currentTimeMillis()-duration > TimeUnit.DAYS.toMillis(10)) {
// inflateDialog is a function containing the functionality of popping up the dialog
Dialog dialog = inflateDialog(R.layout.dialog_layout);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putLong("duration", System.currentTimeMillis())
.apply();
}
}
I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");
I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above
So my question might have been asked many times but i couldnt find an answer anywhere on the internet to it .
. What i want to do is store a textview using sharedprefeences .
In my first class (xp) i,m sending the textview to another class (feedback)
Now the feedback is reciving the textview with no single problem , but never saves it. How can i store that textview in the (feedback) class even after closing the app ??
Here's the class which is intenting the textview
public class Xp extends Activity {
Button accept;
TextView textV;
TextView xbnum;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xp);
accept = (Button) findViewById(R.id.accept);
textV = (TextView) findViewById(R.id.textV);
xbnum = (TextView) findViewById(R.id.xpnum);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value1 = extras.getString("intent_xp");
final String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString(PREFS_NAME, value);
edit.putString(PREFS_NAME,value1);
textV.setText(value);
xbnum.setText(value1);
edit.commit();
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Xp.this, feedback.class);
i.putExtra("intent_extra", textV.getText().toString());
startActivity(i);
finish();
}
});
}
}
}
And here is the class which will recive the intent and save the textview (As supposed )
public class feedback extends Activity {
TextView test1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
test1 = (TextView) findViewById(R.id.test1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences("intent_pref", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("intent_pref",value);
test1.setText(value);
edit.apply();
}
}
}
The class is reciving the text , and everything is okay . Only when i close the app and open it , everything is cleared out ..
May be I'm wrong but it seems that you missunderstood how shared preferences works.
If you want to store several values in a preferences file an access it in others classes you have to create one instance of a SharedPreferences.
In your case it means create in both "feedback" and "Xp" a SharedPreferences instance like this :
SharedPreferences settings = getSharedPreferences("MyPrefsFile", SharedPreferences.MODE_PRIVATE);
and then use this instance to store your datas with an editor.
Be careful if you can't store several value for the same key.
You can also store your value in several files as you are actually doing. But if you want to set your textview with the value of your preferences file you have to get it with the getString("key_of_your_value") method on your shared preferences instance.