I have multiple applications that share certain data through preferences. Each app sets its preferences through a PreferenceActitivity (from xml). Two questions:
How do I use/edit preferences created by one app in another app. If I figure out how to create MODE_WORLD_WRITEABLE preferences using PreferenceActivity that will solve the problem.
SharedPreferences prefs = getSharedPreferences(
<String referring to another package´s prefs>, MODE_WORLD_WRITEABLE);
HashMap<String, String> map = (HashMap<String, String>) prefs
.getAll();
String str = map.toString();
tv.setText(str);
Above code returns {}
Second, how do I use addPreferencesFromIntent(i) -- I am getting a NullPointerException even though the intent is not Null.
Thanks for the help in advance.
Best,
Sameer
To access preferences from another app in a secure way set the same android:sharedUserId in the Manifest. This will allow you to access preferences & files in MODE_PRIVATE (or secure) manner.
After much time spent, we realized this alone will not work and one needs to create a package context of the first app to access files in the second app:
try {
Context c = createPackageContext(com.app.first, MODE_PRIVATE);
SharedPreferences prefs = c.getSharedPreferences(
"com.app.first_preferences", MODE_PRIVATE);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
A big thank you to #CommonsWare and Karthik Shanmugam for their help!
Related
I am new in Android Development. I am trying my hands on developing an alarm app. When I set the alarm, I use a TextView to show the time for which the alarm in set up(initially empty). But when I close or minimize the app and start it again the TextView is again empty. How to get rid of this?
I looked for its solution in android app development manual, but still couldn't find my way out.
Particularly visiting developer.android.com will help you to get started with android development. Anyways you can either use any of the following to save your data:
SharedPreferences
Sqlite Database
File (Pertaining to your app's location)
And when you are reopening your application you can retrieve the information from this methods.
Saving data can be done easily with the SharedPreferences.
private final String SAVED_ALARM_TIME_KEY = "SavedAlarmTime"
private final String ALARM_PREFERENCES = "AlarmPreferences"
private void saveAlarmTime(Context context, long alarmTimestamp) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong(SAVED_ALARM_TIME, alarmTimestamp);
editor.commit();
}
private long getAlarmTime(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
return sharedPref.getLong(SAVED_ALARM_TIME, 0);
}
This is great for something like user settings in the application. But I imagine you will later want to add multiple alarms to your application. In this case it would be better if you used a database. It will provide you with more options to scale the implementation. For instance you wish to add a functionality for repeating alarms at certain days the database will come in very handy.
You can refer to the documentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
I'm trying to write a file on users mobile following this example
Storage Options [data-storage]
I want to create that file the first time users run my app.
After the first time users run my app, I want FIRST read the file, and THEN write something in it (if i need).
Following the example above i'm using FileInputStream stream= openFileInput(FILENAME),
Is there a way to know if the file i put in FileInputStream exists by checking the fIleInpuStream itself?
Thank everybody for your help.
Maybe the best way to do what i want to do was suggested by #Durairaj P.
I used Preferences.
But i'm still wondering if it's suitable and appropriate for what i want to do. I want to keep track of the points that users earn while playing my game; when users re-open my app, i have to show all the points they earned since they installed my app. I'm just wondering if Preferences are suitable and appropriatefor this, or if i should use something else.
Anyway i post my code, it might help someone
public class managePreferences{
Context context;
managePreferences(Context context){
this.context = context;
}
public String readPreference(String fieldName, String defaultValue){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
String value = prefs.getString(fieldName, defaultValue);
return value ;
}
public void writePreference(String fieldName, String value){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(fieldName, value);
editor.commit();
}
}
I would use
context.fileList();
and test if my file is somewhere. (quickest way is to make a List of it and use contains()) :
Arrays.asList(context.fileList()).contains(FILENAME);
I have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.
the document
http://developer.android.com/guide/topics/data/data-storage.html
shows that there are multiple ways to save data, I need to do this in a widget and everytime I try to save i get errors...
for instance
SharedPreferences settings = getSharedPreferences("NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", false);
// Commit the edits!
editor.commit();
Error
Description Resource Path Location Type
The method getSharedPreferences(String, int) is undefined for the type AWidget
another attempt:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
with error
Description Resource Path Location Type
The method openFileOutput(String, int) is undefined for the type AWidget
whats the deal? I see no mention this does not work in a widget so why is it that these examples don't work for me?
What is the preferred way to save this data?
So the issue is is that I cannot just use this function without substance the above code will work fine if I do it with context. in front of it...
SharedPreferences settings = context.getSharedPreferences("NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", false);
// Commit the edits!
editor.commit();
So as you can see that is all that was need to get the shared preferences... and with this...
int[] allids = AppWidgetManager
.getInstance(context)
.getAppWidgetIds(new ComponentName(context, AwarenessWidget.class));
I can get all the IDs of my app and call onupdate and update each ones views based upon the saved preferences
I can elaborate more if anyone needs...
Baffels me no one was able to figure that one out and help me! seems very straight forward now!
I think if you want to save state about a particular widget it's best to use the saved state mechanic built into the View framework. SharedPreferences are sort of global to the Application. So if you had two instances of AWidget it would be rather hard to differenciate between the two at runtime.
Instead you might want to override:
onRestoreInstanceState(Parcelable state)
onSaveInstanceState()
If save is enabled for your View, Android should call onSaveInstanceState() where your widget will have a chance to return a Parcelable that it can use later in onRestoreInstanceState() to resume where it took off.
Currently, I'm using the following code across all of my activities in my app to store application level variables and carry values between activities..
prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
I didn't have a PreferenceActivity prior to this, but now I do and I am looking to store a few user prefs from this new PreferenceActivity in the same sharedPreferences tag, "MyPrefs".
I know I can access the PreferenceActivity SharedPrefs from my activities via
prefs = PreferenceManager.getDefaultSharedPreferences(this);
but I would like those values saved to my current sharedPreferences tag, "MyPrefs", but I'm not sure how to do this.
Thanks in advance..
You can change the default name of SharedPreferences file used by PreferenceActivity.
I did this in onCreate method of PreferenceActivity by adding the following piece of code:
getPreferenceManager().setSharedPreferencesName("MyPrefs");
Yes, you can http://idlesun.wordpress.com/2011/04/08/how-to-make-preferenceactivity-use-non-default-sharedpreferences/
You can't. the PreferneceManager always uses this.getPackageName () + "_preferences as preference name. Sorry to break the bad news. This is also important when you wish to use the new backup framework.
You can of course replace MyPrefs with this.getPackageName () + "_preferences.