Original Post:
In the following example:
How to save and retrieve Date in SharedPreferences
What should I be looking to replace the ... with?
Save:
SharedPreferences prefs = ...;
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", date.getTime());
editor.commit()
I'm attempting to use something such as:
SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);
but I'm getting an error stating DATE_PREF cannot be resolved to a variable.
MY SOURCE:
//get the current date
Date date = new Date(System.currentTimeMillis());
// convert the date to milliseconds
long millis = date.getTime();
// save the date to shared preferences
SharedPreferences prefs = millis ;
SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);
editor.putLong("time", date.getTime());
editor.commit();
Update After First Response: (Help Still Needed)
After removing the lines:
// SharedPreferences prefs = millis;
// SharedPreferences.Editor editor = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext())
I'm getting two errors stating "editor cannot be resolved" at:
editor.putLong("time", date.getTime());
editor.commit();
due to the fact I removed the lines which referenced the editor - my question is: will my preferences still be saved as shown below? (I need this value to persist after reboot.)
I've tried using:
SharedPreferences.putLong("time", date.getTime());
SharedPreferences.commit();
as well as:
putLong("time", date.getTime());
commit();
However both methods are causing errors and I just want to make sure the values will be stored after reboot.
public class WifiMonitor extends Activity {
Button sendButton;
EditText msgTextField;
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView) findViewById(R.id.traffic_info);
// get traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.##");
String totalStr = nf.format(totalBytes);
String mobileStr = nf.format(mobileBytes);
String info = String.format(
"Wifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
mobileStr);
infoView.setText(info);
// send traffic info via sms
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("7862611848", null, info, null, null);
String alarm = Context.ALARM_SERVICE;
// get the current date
Date date = new Date(System.currentTimeMillis());
// convert the date to milliseconds
long millis = date.getTime();
// save the date to shared preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// SharedPreferences prefs = millis;
// SharedPreferences.Editor editor = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext());
editor.putLong("time", date.getTime());
editor.commit();
// get the saved date
Date myDate = new Date(prefs.getLong("time", 0));
}
// set the alarm to expire 30 days from the date stored in sharePreferences
public void invokeAlarm(long invokeTime, long rowId) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, Alarm.class);
i.putExtra("rowId", String.valueOf(rowId));
am.set(AlarmManager.RTC_WAKEUP, invokeTime, PendingIntent.getService(
this, (int) System.currentTimeMillis(), i, 0));
}
}
PreferenceManager.getDefaultSharedPreferences(context);
Context can be getApplicationContext().
Related
I am Working on a project where i have two buttons and a textview (in layout) for a time picker to set notification,
buttonTimepicker & buttonCancelAlarm.
I used to save the Time, selected in the Time Picker by shared Preferences.
The shared preferences are working properly.
But the problem i am facing is that, when i click the Cancel button, My app still showing me the notification set by time picker, Even i had implement editor.clear(); on shared preference on click of Cancel button Listner.
When i remove the shared preferences it work properly canceling the time and notification.
Here, what i want is to save the time in a shared preference on Set Time button, And clear shared preference on cancel Time button.
public class drvschedule extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
private TextView mTextView;
SharedPreferences myPrefdrv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drvschedule);
mTextView = findViewById(R.id.drtmslctd);
Button buttonTimePicker = findViewById(R.id.setdrvtm);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
Button buttonCancelTime = findViewById(R.id.cncldrvtm);
buttonCancelTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
cancelAlarm();
}
});
myPrefdrv=getPreferences(MODE_PRIVATE);
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Notification set for Driving: ";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
timeText +=
DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
}
mTextView.setText(timeText);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Notification canceled");
}
}
//used to save preferences....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
//used to clear preference....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
Please try this code To store ,get and clear sharedprefereces data
we have pass two parameters in this method getsharedpreferences(String PREFS_NAME ,int mode )
PREFS_NAME is the name of the file.
mode is the operating mode.
StoreData
SharedPreferences pref = getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("deviceToc",token); // Storing string
editor.apply();
getData
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
SharedPreferences prefs = sharedpreferences;
String string = prefs.getString("deviceToc", null);
clear data
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
sharedpreferences.edit().clear().commit();
You can use this instead of time picker
editors.putLong("lastlogin", new Date().getTime());
this answer
This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
I have this button code and it was connect to database
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
String email = jsonResponse.getString("email");
String alamat = jsonResponse.getString("alamat");
int notelp = jsonResponse.getInt("notelp");
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("alamat", alamat);
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Login Gagal")
.setNegativeButton("Ulangi", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
i have a table called admin thats contain field name, email and etc.. how can i take the data from databse then save my data like name, email, alamat and the other to shared prefences. then can you help me to call it to another activity?
First of all you have to create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE);
Editor edt = pref.edit();
To add value in preference:
edt.putString("name", name);
edt.putString("email", email);
edt.putString("alamat", alamat);
edt.putString("notelp", notelp);
edt.putString("username",username);
// Save your changes
edt.commit();
Now for getting data from preference:
String name=pref.getString("name", null);
String email=pref.getString("email", null);
String alamat=pref.getString("alamat", null);
String notelp=pref.getString("notelp", null);
String username=pref.getString("username", null);
If you want to clear the preference data:
edt.clear();
edt.commit();
Save like below.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
getPref.edit().putString("name",name).apply();
intent.putExtra("email", email);
getPref.edit().putString("email",name).apply();
intent.putExtra("alamat", alamat);
getPref.edit().putString("alamat",name).apply();
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
Retrieve like this.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
String name = getPref.getString("name","");
String email = getPref.getString("email","");
String alamat = getPref.getString("alamat","");
Create a class SharePrefUtil
private Context context;
private SharedPreferences prefs;
public SharePrefUtil(Context mContext) {
this.context = mContext;
prefs = this.context.getSharedPreferences("your package name", Context.MODE_PRIVATE);
}
public void setValueInSharePref(String keyName, String value) {
prefs.edit().putString(keyName, value).apply();
}
public String getValueFromSharePref(String keyName) {
return prefs.getString(keyName, "");
}
}
When ever you want to store the value
Just Make a object of class in you activity to get or set a value
for example
SharePreUtil shef = new SharePreUtil(this);
When ever you what to set a value in the activity
shef.setValueInSharePref("key", "yourvalue");
when you want to get value
shef.getValueFromSharePref("key");
All the best...
onCreate() method
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
to get all data server after
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(name, name);
editor.putString(email, email);
.....
editor.commit();
quoting the training guide at https://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
and to read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
In your other activity....first receive data from intent...like this
String name = getIntent().getExtras().getInt("name");
now,save this data into shared prefrences....to do that...you need sharedPreferences.Editor to write data.....like this...
SharedPreferences sp = Your_Activity.this.getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
SharedPreferences.Editor spwriter = sp.edit();
spwriter.putString("name",name);
spwriter.commit();
if (success) {
// once you retrieve all the required data
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Writing data to SharedPreferences
Editor editor = prefs.edit();
editor.putString("name", name);
editor.putString("email", email);
editor.putInt("notelp", notelp);
editor.commit();
// start your AdminArea activity here
}
Retrieve data inn AdminArea class:
// Reading from SharedPreferences
String value = prefs.getString("name", "DEFAULT_STRIGN"); // if the given key not found, it'll take the default string as value
int intValue = prefs.getInt("notelp", -1); // instead of -1, you can give any default value
hope this helps :)
You can save data in SharedPreferences in your activity class as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.putString("email", alamat);
editor.putString("alamat", alamat);
editor.commit();
And in your activity where you want to fetch them, do as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name", "abc");
String email=sharedPreferences.getString("email", "abc#gmail.com");
To put int,
editor.putInt("number",0);
And to retrive it,
sharedPreferences.getInt("number",0);
I'm storing some values in my PreferencesFragment in this way:
// SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = getPreferenceScreen().getSharedPreferences();
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
Then, I want to read the preferences in a non activity class:
// SharedPreferences prefs = ActivityHandler.getCurrentActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = ActivityHandler.getCurrentActivity().getPreferences(0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
I've tried also the uncommented code, but I get always 0 for both values.
Try this
Store with SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("my_pref", Context.MODE_MULTI_PROCESS);
Editor editor = sharedPref.edit();
editor.putInt("KEY", VAL);
..
..
editor.commit();
Retrieve from SharedPreferences
SharedPreferences sharedPref = getSharedPreferences(
"my_pref", Context.MODE_MULTI_PROCESS);
int size = sharedPref.getInt("KEY", default_VAL);
This will be helpful...thanks
You are doing it wrong. Each time you are getting a different shared preference. Use this code:
For storing value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
For fetching value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
Hope this will help you.
I'm trying to create something that needs to get information in the first time and save it. The app starts at the MainActivity, if it does not have the information needed, the app send you to the MotoActivity. Once the app has the information you don't need to go to the MotoActivity anymore. I know i'm wrong but I don't know how to do.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("valid", 0);
editor.commit();
int n = sp.getInt("valid", -1);
if(n == 0){
editor.putInt("valid", 1);
editor.commit();
startActivity(new Intent(MainActivity.this, MotoActivity.class));
MainActivity.this.finish();
}
First check for the very first time that, if "userLoggedBefore" is true or false from the SharedPreferences, if the user had used the application before and had entered the right credentials, we will save authenticated to true and if he hasn't we will set the default value as false.
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false);
then check -
if (authenticated){
//show your MainActivity
} else {
// show your MotoActivity
}
in your MotoActivity,
//if credentials matches
if(credentialMatches)
SharedPreferences sharedPref = getSharedPreferences(
"Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", true);
prefEditor.commit();
else{ // if credentials doesn't match
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", false);
prefEditor.commit();
}
Try this:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// app already has the needed info.
if(sp.getInt("valid", -1) == 1){
// do something
}
// app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1
else{
startActivity(new Intent(MainActivity.this, MotoActivity.class));
finish();
}
I have an activity class which will scan an NFC tag and assign it to a string (this part is functioning fine) the string is then shared via sharedpreferences which then updates a textview (among other things). For some reason the textview never seems to update with the text from the NFC tag. It should be a simple enough problem to solve - I simply cannot get the NFC data which is assigned to a string to update the textview via sharedpreferences and I'm not sure why.
CONNECT.JAVA CODE SNIPPET:
// after scanning - splitting the message by comma
String[]tagdata=msgtext.split(",");
String networkSSID = tagdata[0].toString();
String networkPass = tagdata[1].toString();
String time = tagdata[2].toString();
String restricted = tagdata[3].toString();
String corename = tagdata[4].toString();
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
// editor.putBoolean(time, true);
editor.putString("time", time);
editor.putBoolean(restricted, true);
editor.putBoolean(corename, true);
editor.commit();
RULES.JAVA CODE SNIPPET: (where the time textview is shown - but never changes)
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE);
boolean name = prefs.getBoolean("name", true);
boolean code = prefs.getBoolean("corename", true);
//boolean time = prefs.getBoolean("time", true);
String time = prefs.getString("time", "");
boolean ssid = prefs.getBoolean("restricted", true);
Time.setText(String.valueOf(time));
//String time = String.valueOf(time);
Intent intent2 = new Intent(Rules.this, KillTimer.class);
PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
0);
AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
time ? 1000 : 0, pintent2);
editor.putString("name", name) and so on and prefs.getString("name", "");
Instead of
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
in CONNECT.JAVA you should use
SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE);
When you call getPreferences the preference is private to the activity.