Error while accessing Shared Preference of my App - android

I am not able to access shared preference data. I have already checked in another URL for this error. Error is...
remove failed: ENOENT (No such file or directory) : /data/data/com.example.lenovo.sms/shared_prefs/refresh_token.xml.bak
Code for storing and accessing data in shared preference
private void saveToken(String recent_token) {
saveTokenPref = getSharedPreferences(Config.SAVE_TOKEN_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveTokenPref.edit();
editor.putString(Config.TAG_TOKEN,recent_token);
editor.commit();
}
public String getSavedToken() {
saveTokenPref = getSharedPreferences(Config.SAVE_TOKEN_FILE,Context.MODE_PRIVATE);
String saved_token = saveTokenPref.getString(Config.TAG_TOKEN,"");
Log.d("save token",saved_token);
return saved_token;
}

In onCreate():
saveTokenPref = PreferenceManager.getDefaultSharedPreferences(this);
Then, use the below codes:
private void saveToken(String recent_token) {
SharedPreferences.Editor editor = saveTokenPref.edit();
editor.putString("token",recent_token);
editor.commit();
}
public String getSavedToken() {
String saved_token = saveTokenPref.getString("token","");
Log.d("save token",saved_token);
return saved_token;
}
Hope this helps.

Related

default sharedpreferences wont share between activities

i am trying to pass a string set between activities by sharedpreferences but it seems that the default sharedpreferences made two files for each activity.
i tried to share it with PRIVATE_MODE with the same name and it didnt work
SharedPreferences appPrefernces = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor appEditor = appPrefernces.edit();
Set<String> usersSet = appPrefernces.getStringSet("users", new HashSet<String>());
if(!usersSet.contains(id)) {
usersSet.add(id);
appEditor.putStringSet("users", usersSet);
appEditor.apply();
}
SharedPreferences appPrefernces = PreferenceManager.getDefaultSharedPreferences(Main.this);
users = appPrefernces.getStringSet("users",new HashSet<String>());
it seems that it saved the info but while extracting it i get a get just a partial set
In this way you are sure what preferences file you are using:
private static void saveUsers(Context context, Set<String> usersSet) {
final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("users", userSet).apply();
}
private static Set<String> loadUsers(Context context){
final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
return sharedPreferences.getStringSet("users", new HashSet<String>());
}
Hope it helps.

Issue reading data from sharedpreferences. I have to run the app twice before it gets the data stored

I have an issues reading from sharedpreferences in android. The data is stored in the preference file, and i ma sure of this because i used logcat to log the data when i read it back IMMEDIATELY as it was stored as well as i used a toast message to display the data after i read it back from preferences. However when i try to read the data again from a new activity it returns the default of an empty sting. When i exist the app and run it again it read the data that was previously stored. Here is my code for when i initially save the data, it also contains the comments i used to verify that the data stored was read back:
public void downloadMatchesAsync() {
brawtaAPIAdapter.runGetMatches(new Callback<JSONKeys>() {
#Override
public void success(JSONKeys jsonKeys, Response response) {
Log.d(ApplicationConstants.TAG, "blarg");
Success = jsonKeys.isSuccess();
message = jsonKeys.getErrorMessage().toString();
if(!message.isEmpty()){
Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
}
Gson gson = new Gson();
String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'
Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
//data =Preferences.readFromPreferences(activity, ApplicationConstants.match_data, "no data");
//Toast.makeText(MyApplication.getAppContext(), "In networkOperation" + data, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
}
}); // Call Async API
//return data;
}
In a different activity i try to read the data previously written like so:
jsonString = Preferences.readFromPreferences(MatchSelect.this, ApplicationConstants.match_data, "");
but the code only returns the data stored if i exist the app and run it again.
this is my preference class:
public class Preferences {
private static final String PrefName = "net.brawtasports.brawtasportsgps";
public static void saveToPreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String readFromPreferences(Context context, String key, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
}
What is the issue?
apply() is an asynchronous call, so the data doesn't have to be stored immediately. Try calling .commit() instead.

Change from cloud JSON to local JSON

I'm looking at making a change in an app I'm working on (it's based off of this: http://goo.gl/rDBXVl) from loading a cloud based resource to a local based resource. I'm not particularly sure how I would go about doing this. I want to go from pulling a JSON file off the internet to pulling the JSON from my Assets folder.
I located the area in the app where it pulls the URL and loads the JSON but am unsure of what changes to make at this point.
public void loadData (Bundle savedInstanceState) {
// Check Network State
if (!NetworkUtil.getNetworkState(this)) {
final RetryFragment fragment = RetryFragment.getFragmentWithMessage("No connection");
this.addFragment(fragment, RetryFragment.TAG, true);
return;
}
if (savedInstanceState == null || savedInstanceState.get(KEY_LIST_DATA) == null) {
final String url = super.getResources().getString(R.string.config_wallpaper_manifest_url);
if (url != null && URLUtil.isValidUrl(url)) {
// Add Loading Fragment
final LoadingFragment fragment = new LoadingFragment();
this.addFragment(fragment, LoadingFragment.TAG, true);
// Load Data
final RestClientHandler handler = new RestClientHandler(this);
RestClient.get(this, url, handler);
}
} else {
Log.i(TAG, "Restored Instance");
this.mData = (ArrayList<NodeCategory>) savedInstanceState.get(KEY_LIST_DATA);
this.mPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
if (this.mPosition != -1) {
mIgnoreSelection = true;
}
this.configureActionBar();
}
}
You have another option,
just save json in sharedpreferences. so easily read and write it.
Save sharedpreferences code bellow.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}

accessing sharedpreference across applications

I am using getDefaultSharedPreferences(con) in my application to store preferences. Now I want to access this shared preference in another application.
I used following method:
con = this.createPackageContext("com.example.preferences", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences filePref = PreferenceManager.getDefaultSharedPreferences(con);
if(filePref != null){
Toast.makeText(getApplicationContext(), "file pref not null --- ", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "file pref is null **** ", Toast.LENGTH_LONG).show();
}
Map<String,?> allkeys = filePref.getAll();
Toast.makeText(getApplicationContext(), "file pref size **** "+allkeys.size(), Toast.LENGTH_LONG).show();
for(Map.Entry<String,?> entry : allkeys.entrySet()){
Toast.makeText(getApplicationContext(), "~~~ file pref --- map values --- "+entry.getKey() + ": "+entry.getValue().toString(), Toast.LENGTH_LONG).show();
}
Another way which tried is specifying file name & accessing it, as follow;
SharedPreferences filePref = gvcon.getSharedPreferences("com.example.preferences_preferences", Context.MODE_PRIVATE);
With this method I am able to access SharedPrefernce file, it returns file is not null but when I check for file size it shows 0. I am not able to read preference value from file.
I used shareduserid of another application so that I get full access to that application.
What is the proper way to go about this?
I'm not sure that I understood your problem completely, but some times this implementation will help you to access data across packages.
Use getSharedPreferences() to store data in shared preferences
This method will store data in shared preferences
public void dataWriter(){
String strShareValue = "Hello! this is shared data";
SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();
}
You can access that shared data from another package using this code sample
public void dataRead(){
Context con;
try {
con = createPackageContext("PACKAGE NAME THAT SHARES DATA", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
String dataShared = pref.getString("demostring", "No Value");
}
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}
}
}

About another Application to visit SharedPreference

I need visit the sharedPreference of another application, the SharedPreference have to set
"MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE" , and show you the Logcat.
03-23 13:54:45.038: E/ApplicationContext(10895): Couldn't rename file /data/data/com.mzw.gamehelper/shared_prefs/public.xml to backup file /data/data/com.mzw.gamehelper/shared_prefs/public.xml.bak
I dont know what's wrong with it, who can help me, thank you.
try this code insert values
private SharedPreferences myPrefs;
myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Mobile_no", getText_no.getText().toString().trim());
prefsEditor.commit();
and try this code get values
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
myPrefs.getString("Mobile_no", "");
TRY THIS WAY ::
Context otherAppsContext = null;
private SharedPreferences sharedPreferences;
public static final String PREFS_READ = "PREFS_READ";
public static final String KEY_READ = "KEY_READ";
try {
//com.dfdf.fdfdf.android.sharedpreferences OTHER APPLICTION PACKAGE NAME
otherAppsContext = createPackageContext("com.dfdf.fdfdf.android.sharedpreferences", 0);
} catch (NameNotFoundException e) {
}
sharedPreferences = otherAppsContext.getSharedPreferences(PREFS_READ, Context.MODE_WORLD_WRITEABLE);
String strvalue=sharedPreferences.getString(KEY_READ, "WORLD READ EMPTY")

Categories

Resources