Preference Screen as interface for database? - android

Is it possible to use a preference screen as a simple interface to read and write values to a database?
Basically, I like the way the preference screen looks and operates, but preferences aren't a suitable way to store all the data I have.
I know how to get it to display correctly, but I'm unsure on how to access the values represented on the screen, and how to keep it from writing a preference file.
Is this even a good idea?
Thanks.

Just to follow this up for anyone that is interested. I got it working by using a Preference.OnPreferenceChangeListener() to store the value as a int or string or whatever. For example:
et_model.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference preference, Object newValue) {
String val = (String) newValue;
preference.setSummary(val);
model = val;
return true;
}
});
Then once the user presses done, I add the data to the database in the usual way with my SQLight database helper class.
When I load the values from the database, I simply use Preference.SetText(String), and Preference.SetSummary(String).
I guess it is still writing a preference file because if I don't set the preference's text it will load with whatever was set last, but I don't think this is a problem. I could also delete the preference file when I close the activity or something...
If you want a good example, just look at the source for the AlarmClock (now DeskClock) Look at SetAlarm.java and set_alarm.xml for the layout(Save and cancel keys) and alarm_prefs.xml for the actual preference layout.

I don't think that is such a hot idea, especially if you plan on having a tone of data in your database. How ever if you did want to do it, I would just extend the Preference widgets that you will use and have them interface with the database. For example, lets say you have 10 items in a table and you want to select one item (row in the database), you would override the ListPreference and fill it with the content of the applicable database row.

Related

Save User-Created views (e.g. buttons and text views) to be restored when using the app again

My Activity has 6 default CardViews, each cardview contains a Constraint layout and the constraint layout contains a couple of Text views
my problem is, I wanted to add an "ADD" which would take you through some steps and eventually create a new cardview, but how would I save that view created by the user so when they close the app and enter again it would still be there? (Users could add multiple cardviews)
I'm familiar with SharedPreferences but i don't think it would be possible in this case because it requires me to save the data in a declared string and the user simply doesn't have access to that
What i want to do is something similar to Alarm apps, when you can add multiple alarms, delete alarms etc and it would be there even if you restart the Alarm app
What you need is not saving the view itself, but rather save info or state of each object after user modifies it. And you are right about SharedPreferences, it wouldn't be the best option for this...
So, I would recommend two things:
Saving & getting your Cardviews data should be from a custom class (for ex: Alarm) that has properties.
package my.app.example;
class Alarm{
long time;
boolean isOn;
String label;
public Alarm(long time, boolean isOn, String label){
this .time = time;
this .isOn = isOn;
this .label = label;
}
}
And you can use it as follows:
long timeFromDatabase = ...;//get time value from database
boolean isOnFromDatabase= ...;//get isOn value from database
String labelFromDatabase= ...;//get label value from database
Alarm alarm1 = new Alarm(timeFromDatabase, isOnFromDatabase, labelFromDatabase);
After, you can add each Alarm object to a List, and then pass it to your Adapter
A database (I recommend Sqlite or Json) to which you will save each Alarm data (time, isOn, ...)
Remark Alarm is just an example! Feel free to use whatever name and properties that suit your project
See this tutorial it's way is similar to what I suggested: https://www.javatpoint.com/android-sqlite-tutorial, he saves contacts to an sqlite offline database and get them later.

Android application remember settings

I am coding using Xamarin and have a question about application settings.
Is it possible to have application wide settings? I will give you an example:
I have a map application. I have a ListView where the user can select if the map is using the Street View, Satellite View or default view.
Depending on the item that is selected in the ListView depends of the map view that is shown.
Where and how can I save this selection such that this value is visible throughout the application and when the user exits the application, this setting can be remembered for when the user starts the application up again?
Thanks in advance
Yes, it's possible and also very easy. Usually you save simple application settings using SharedPreferences. They can be read from anywhere in the app.
For writing.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putBoolean("someBoolean", true);
editor.putString("someString", "string");
editor.commit();
For reading
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean someBoolean = sp.getBoolean("someBoolean", false);
boolean someString = sp.getString("someString", null);
I suppose you are familiar to Java I/O and android basic concepts. So here I go:
For data persistance in Android, you have two main solutions:
SQLite database
File system
I recommend you to use file system, as you don't really need to organize your data with relational constraints and you will probably not have to make a lot of data persist.
Android documentation is very clear on how to save files:
http://developer.android.com/training/basics/data-storage/files.html
I recommend you to create a Setting class that contains a HashMap attribute:
public class Settings implements Parcelable{
public static HashMap<String,String> settings;
public static void readSettings(){
//Here you read your settings file and you fill your hashmap
}
public static void writeSettings(){
//Here you iterate through your hashmap and you write your setting files
}
}
Every activities will have access to the settings, as the attribute/methods are static. Settings will also be synchronized through every activities (if you change a setting in one activity, every other activities will notice).
If you need some clarifications, leave a comment below.

Saving data between activities using external class

I'm developing an app that has to share strings between activities. I'm trying to get the seperate activities to call a public class with set and get methods. The calling the methods part works and I manage to get a response although the set value has to be rememberd by the set and get class. Here's a link to my set and get class, it's pretty basic: http://pastebin.com/0WabNKz3
Now my question is this: How do I make the set and get class to remember my values between sessions? Feel free ask questions if there's anything you didn't understand.
Thanks!
You need to use SharedPreferences. That's the way to save data even after the app is closed and you can access it from anywhere:
public void savePrefrences(String key, String value)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
prefs.edit().putString(key, value).commit();
}
public String getPrefrences(String key)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
return prefs.getString(key, "");
}
Save the prefrence when and whereever you want and get it whenever and from wherver you want.
The value will not delete when you close the app.
I ended up creating invisible EditTextPreference that now hold the data that I want to keep because they can be shared easily.
When you say saving between sessions, do you mean between the app being paused, or closed completely?
A good resource for lifecycle and storing data across sessions is:
//developer.android.com/training/basics/activity-lifecycle/index.html

StoreData even phone rebooted

My app has this appearance
It seems to be a TableLayout with several TableRows. In my activity, each TableRow has 3 views: ImageView, TextView and a Button.
The user is the one who sets the content of the ImageView and the TestView by entering the text he wants and pressing a button.
I store this data in stringArray variables and works fine if the phone is not restarted or the app is not closed (forceClose)
If one of these two situations happen, i lose all my data.
I've been trying to store my StringArrays by SharedPreferences but I don't know when i should load the preferences, whether it's in OnCreate() or OnResume() or OnStart methods().
Another question is how to define the arrays. I use this:
String[] titulo = new String[500];
I don't know if this string is created each time i start the activity. Because what i want is to load the previous String (from SharedPreferences) and add some more entries not to create new ones every time the phone is rebooted, for example.
Do you think i need a SQL database or it's OK with this StringArrays.
Thank you.
You should probably switch to using a database, seeing as you have an array of size 500, which could possibly increase in the future.
However, if you want to continue using SharedPreferences, you should write the data in onPause() and onStop() methods, and use an if else statement to see if your data is null before running an operation on it. If the data is null, the read it from the SharedPreferences before continuing.

Preferences - using media files, images

I’m a new developer, so my question maybe too much basic.
I look for example of defining preferences of sound. User can choose what kind of sound will start an application, for example. There can be such a RingtonPreference widjet, so user can choose a sound.
As I know, preferences support the primitive types: Boolean, string, float, long and integer. What way is the best to design preferences: store in entryValues the names if sounds (strings), the address of files from Resourse class (integer), or other way.
Please provide a short example of code.
Thanks in advance!
First of all thank you for the quick and detailed answer!
I want to arrange list of sounds: there must be one “None”, list of sounds that contains folder “raw”, option to add a new sound from different locations and two buttons: “set” and “cancel”. When user touches one item from the list – sound starts to play.
There is a little problem with standard widget that provide android library. “ListPreference” isn’t appropriate because on touch on one of the items – item is chosen and list closes, “there are not buttons set and cancel”.
“RingtonPreference” isn’t appropriate as well – I didn’t succeed to add something to list.
How is possible to build a custom preference layout and that is options that were chosen will be saved as well as on standard widgets. Please provide a short code example. Thanks in advance!
I think the best way to store the Resource are by integers. or you could do names.
I think integer is more reliable.
So to use SharedPreference with this you will need to get access to the apps SharedPreference
public class PreferencesDemo extends Activity {
SharedPreferences app_preferences;
private int resourceNumber;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
resourceNumber = app_preferences.getInt("resourceNumber", 0);
if(resourceNumber == 0){
//This means the user hasnt selected a song and you must act accordingly. Or put a resource number where the 0 is do set it to a default song
}
You will probably want to create a method to put the songs in the SharedPreference such as;
private void createSongResouces(){
SharedPreferences.Editor editor = app_preferences.edit();
//Here you can put as many songs as you want just make sure you call editor.commit(); as i do.
editor.putInt("resourceNumber", resourceNumber);
editor.commit(); // Very important
}

Categories

Resources