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);
Related
In my Android application for my school project I want to make it such that:
Every day, when you first open the application, it will start an activity. However, if you open the application again even after closing it from the multitasking view, it will not start the activity again.
I want it to be much like Elevate (https://www.elevateapp.com/) where on first startup it will say "Your training session for the day is ready" but never display this again if you open the app at another time in the day.
This is a screenshot of the activity:
I have tried using AlarmManager in this link Alarm Manager Example and searching for answers but it did not work for me and I couldn't find any.
Is there a way to make it possible? Thanks in advance.
We can use SharedPreferences to store the system date when the app is launched and verify if it is the same date or a different one every time the app s run.
If the date is different, store the new date into the SharedPreferences handle that you used.
To understand how to use SharedPreference to store data you can look at my answer here for an example.
First declare this two method on global level
public static void commitPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String readPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
now maintain your logic..
if (!readPref("CHECK_IF_RUN_TODAY", getApplicationContext()).equals(new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()))){
//YOUR LOGIC
commitPref("CHECK_IF_RUN_TODAY", new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()), getApplicationContext());
}
but dont forget to upadte your prefrence after your logic
Hope this helps..
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 am making an app that is able to log in. Each time the user log in, the app will retrieve user data and save it locally so that each time user need to do something which need user information, the app need not to retrieve it again. Is it better to put it in a SharedPreferences or SQLite?
Since it will be always only one user data need to be stored, I think to put it in a SharedPreferences, but it makes my app have so many key-value data. I am also able to use SQLite instead. But, it looks awkward to have a database that always only have one record data in the table.
Is it a good practice to put only one record data in a database and keep replacing it once the data changes? Or is it better to put it in a Shared Preferences and make the SharedPreferences a bit messy because it has many key-value data.
I think SharedPreferences is best way to store profile data....
In SharedPreferences also we can replace stored data.
public class SharedPref {
private SharedPreferences pref;
private Editor editor;
private Context context;
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREFER_NAME = "SharedPreferences";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
#SuppressLint("CommitPrefEdits")
public SharedPref(Context context){
this.context = context;
this.pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
this.editor = pref.edit();
}
//Set current tab position
public void setCurrentTab(String currentTab) {
editor.putString(Constant.TabActivity.CURRENT_TAB,currentTab);
editor.commit();
}
public void setTabActivityTitle(String title) {
editor.putString(Constant.TabActivity.TAB_ACTIVITY_TITLE,title);
editor.commit();
}
public String getSessionValue(String key) {
return pref.getString(key, null);
}
}
It totally depend on your data, which you want to store. I would personally recommend you to store in sharedpreferences. SQLite is used to store large, Structured and Organized data where as sharedpreferences are used to store small, unstructured data like login info, user preferences etc
I would use SharedPreferences for your scenario.
A database would be good if you had several user profiles, but since you only want to store one user profile, it doesn't make sense to create a database for just one row.
You shouldn't use neither SQLite nor SharedPreferences, the thing is, android done it for you, you should something that's called AccountManager
Why you should it:
This class provides access to a centralized registry of the user's online accounts. The user enters credentials (username and password) once per account, granting applications access to online resources with "one-click" approval.
You can read about this class here : http://developer.android.com/reference/android/accounts/AccountManager.html
But what you should know is that you can also remove accounts there, so it's especially good for you, here is tutorial Step by step: http://www.finalconcept.com.au/article/view/android-account-manager-step-by-step-2
I've placed a preferences file 'xml/sleeppreferences.xml' into a tabSpec, with the idea that that is the preferences for that part of the app and there will be other preference files for other parts.
This seems to work ok. I make a preference change, close the emulator, re-run the app, go back to the preference page, and the preference is what I had set it to.
But when I click to another tab, where I want to use the value of that preference, it all goes wrong.
I've looked high and low, but cannot find an answer.
This is an excerpt of the code:
public static final String PREF_FILE_NAME = "sleeppreferences";
:
:
:
SharedPreferences prefs = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
String test=prefs.getString("editTextPref", "unset");
with "unset" being the default response if it doesn't find anything.
It always returns "unset"
As I say, I've looked all over, and the code I'm using seems to be the correct code. So what's going on?
Thanks
Dave
Try using the GetSharedPreferences of the context class. Something like this:
public String GetPassword (Context Contexto, String Key) throws Exception
{
SharedPreferences savedSession= Contexto.getSharedPreferences(Key,Context.MODE_PRIVATE);
return Encryption.decrypt(_Seed,savedSession.getString(Key, null));
}
I think this should work as well:
getApplicationContext().getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE).getString("editTextPref", "unset");
Please, try this code to save your preferences and then use the code I previously pasted. It has to work fine.
SharedPreferences savedSession= context.getSharedPreferences(Key,Context.MODE_PRIVATE);
Editor editor = savedSession.edit();
editor.putString(Key, EncryptedPass);
editor.commit();
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!