Storing Intent object to SharedPreferences - java

I'm trying to save an Intent object to SharedPreferences and the result code from onActivityResult() so I can use it later. I have already tired to store it as a json using Gson, but there is data loss. I have also tried to save it as uri, but the Intent.toURi() method returns empty string or a string that is not complete. Is there any other way to save it than as a string ? The intent has extras and I need to save all of its data, not just some parts of it.
This is what I've tried for storing it as uri:
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
String uriString = data.toUri(0);
editor.putString("SavedIntentData", uriString);
editor.putInt("SavedResultCode", resultCode);
editor.apply();
and for restoring it:
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
String intentData = settings.getString("SavedIntentData", null);
int resultCode = settings.getInt("SavedResultCode", 0);
if(resultCode !=0 && intentData != null) {
data = Intent.parseUri(intentData, 0);
}
And for json:
String intentData = new Gson().toJson(data);
to restore it:
data= new Gson().fromJson(intentData, Intent.class);

Related

Sharedpreferences android studio error saving data [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I saved my data from an numberDecimal edit text using sharedpreference. When I want to get that data in another activity, it always appears as null, so it wasn't saved correctly. Any suggestion?
This is my code from where I save the data :
public void Start(View view) {
EditText LevelEdit = (EditText) findViewById(R.id.editText_LevelCurrent);
String User_Level = LevelEdit.getText().toString();
if (User_Level == "") {
Toast.makeText(this, "Select a level",
Toast.LENGTH_LONG).show();
} else {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(GameConstants.StringvalueOfLevel,User_Level);
editor.commit();
Intent myIntent = new Intent(Mygame_Menu.this, Mygame.class);
startActivity(myIntent);
}
}
i think your condition is wrong and because of that your saving null object in shared preference don't check the string like this if (User_Level == "")the == operator dose not work on the strings in java ! you should use equals method for comparing to String like this "Amir".equals("Amir")
use this instead if (User_Level==null||User_Level.isEmpty())
You are missing to put sharedPreference name as parameter causes error.
Instead of this
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Change
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPreferenceName",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
You can't compare string value with int format in if loop. Change
if(User_Level == "")
To
if(User_Level.equals(""))
So it will check the condition as correct. Otherwise above will execute else part even if its null.
EDITED
private static final String PREFS_NAME = "PREF_LEVEL_DATA";
private static final String PREFS_KEY = "LEVEL";
public void SaveLevel(Context context, String level) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREFS_KEY, level);
editor.commit();
}
public String RetrieveLevel(Context context) {
String level;
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(PREFS_KEY)) {
level = settings.getString(PREFS_KEY, "");
} else {
return "";
}
return level;
}
For store a value
SaveLevel(getApplicationContext(), User_Level);
For retreive a value
String level = RetreiveLevel(getApplicationContext());
UPDATED
EditText LevelEdit = (EditText) findViewById(R.id.editText_LevelCurrent);
String User_Level = LevelEdit.getText().toString();
if (User_Level.equals("")) {
Toast.makeText(this, "Select a level",
Toast.LENGTH_LONG).show();
} else {
SharedPreferences sharedPref = getSharedPreferences("ANY_PREFERENCE_NAME",
Context.MODE_PRIVATE); //Replace "ANY_PREFERENCE_NAME" as your own string
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(GameConstants.StringvalueOfLevel,User_Level);
editor.commit();
Intent myIntent = new Intent(Mygame_Menu.this, Mygame.class);
startActivity(myIntent);
}

How to use shared preferences to save data that get from database? [duplicate]

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

SharedPreferences Data Still Will Not Update TextView

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.

Ask the user to pick a contact, and then be able to look up that contact's info later?

I'm making an app that will ask for an existing contact, then keep some kind of identifier for that contact, and finally be able to look up that contact's info (specifically, the name and picture) at a later time.
I've got the picker intent:
Intent contactIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactIntent, 5);
and the result:
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (pickCode):
if (resultCode == RESULT_OK) {
Uri contactData = data.getData();
But I'm lost here. How do I "mark down" this contact so I can get to it later?
And once I do that, how do I get the contact picture? Although I can probably figure this out, but if there's some easy way that hooks into the first part, that'd be nice.
You can store this contact uri in SharedPreferences for later use or for sharing between other components as:
Create SharedPreferences as:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("contact_uri", contactData.toString());
prefsEditor.commit();
and for retrieving uri from SharedPreferences later:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
String contact_uri = myPrefs.getString("contact_uri", "not found");
Uri contactData = Uri.parse(contact_uri);

Save intent in shared preference

I have an application from which i can launch other apps installed on my phone, with a long click i get the app picker, in result i receive an intent data, how can i save it so the user when closes an comes back to my app has the same shortcuts setup?
i save other things like this
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label2", label2S);
editor.commit();
But i can't do the same with the intent
Ok i found a way
I save the intent like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
String uriString = data.toUri(requestCode);
editor.putString("Contacts_app", uriString);
editor.commit();
Then i retrieve it like this
SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
String contactsApp = settings.getString("Contacts_app", null);
try {
telApp = Intent.parseUri(contactsApp, 0);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You could serialize the object to a string, and save the resulting string in the preferences. An easy way would be to serialize it in json format, using Google Gson for example.

Categories

Resources