How do I use a SharedPref. in an ArrayAdapter class file? - android

I have a custom Array Adapter to display a list of items, in this case, highscores. The system sort of mimics a folder scheme; one clicks a folder named "Game 1" and it goes to a new list with the top 10 scorers. When you take a test, it changes a sharedpreferences called isPlayed, and if isPlayed is 1, the image for that Game, Game 1, is green, otherwise, if you never play Game 1, isPlayed is never 0, and therefor the image on the highscore list of games is red. But, SharedPreferences seems to be unknown in a class that extends ArrayAdapter. How can I use data from sharedpreferences here? Post a question if you need more info.

You can access SharedPreferences with -
getContext().getSharedPreferences(String name, int mode)

PreferenceManager.getDefaultSharedPreferences(YourActivity.this)
or, instead of YourActivity.this you can use any Context from your application such as your application context.

Related

Android design: user-selected parameters for use throughout app

I'm creating my first game for Android, using Android Studio, and have a design question about choosing and maintaining parameters throughout the application.
From the main menu, the user would select 'New Game', which opens an Activity called 'New Game Parameters', where they would select one option from each of three categories:
Occupation (occupation 1, occupation 2, occupation 3, etc.)
Item taken (item 1, item 2, item 3, etc.)
Action performed (action 1, action 2, action 3, etc.)
Whatever values the user selects will not change again for that specific play-through once the game starts. Depending on the choices, different events will occur, and so I'll need to reference these parameters throughout the game.
My question is, what is the best way to design for that? I've been looking through tons of documentation for BaseAdapter, ArrayAdapter, ListAdapter, Preference, SharedPreference, persistent data, and a lot of it seems viable, but it's been kind of overwhelming and confusing at times. I've gotten a lot of good information from here before, and appreciate any help that you all can provide.
The simplest way to save only a few values (like yours, three parameters with values) is SharedPreferences. There is a good and simple example on this page:
Saving Key-Value Sets
You could also implement some constants to give your key fixed values.
Example of your button (or what you want to let the user choose):
public void onButtonOption1Click(View v){
//Save your value
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("Occupation",1);
editor.commit();
}
Example of activity where you want to load the value:
public void getPreference(){
SharedPreferences sharedPref=getActivity().getPreferences(Context.MODE_PRIVATE);
int occupation_value =sharedPref.getInt("Occupation");
}

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.

Pulling data from one Tab Activity to another

Everything I've read about Intents talks about using them to push data, or to start one Activity from another Activity. I want to pull data from an Activity that's already running.
The Tab Layout tutorial at http://developer.android.com/resources/tutorials/views/hello-tabwidget.html illustrates what I want to do. (My app is doing some engineering calculations instead, but the tutorial code provides a good analogy to my app.) The tutorial creates an app with three tabs, and each tab hosts a separate activity.
To expand on the example in the tutorial, suppose I select an artist in the Artists tab/activity. I want to be able to select the Albums tab/activity and have it display all the albums featuring that artist.
It seems to me that I need to use an Intent to do this. All of the tutorials I've found assume that I would create a "See albums" Button in the Artists tab/activity, and that pressing the Button would execute an Intent that starts the Albums activity and passes artistName.
I DO NOT want to create that Button. Real estate on the Artists layout is precious, and I have a perfectly good Albums tab, AND the HelloTabWidget activity already contains an intent to create the Albums tab.
Besides, a user will want to skip back and forth between Album and Artist in order to change artist selections, and the tabs are a perfectly good way to do this. There's no need to complicate the UI with another button.
So how can I have the Albums activity PULL artistName from the Artists activity when the Albums tab is selected (or the Albums layout is displayed), rather than have the Artists activity START Albums and PUSH the artistName?
Equivalents I can think of from other programming worlds:
Global variables. Discouraged in Android devt, right? And if they do exist, what are they called?
A getter, like artistName = Artists.getArtistName(); . I get the feeling that it's not that easy.
Writing to, and reading from, a file - that is, mass storage or non-volatile memory. I don't need the artistName value to be permanent. It will be reset to null every time the user launches the application.
So how is it done in the Android world? Do I use an Intent - and if so, how?
Global variables were the right answer.
I thought Java discouraged their use, but a couple of links that appeared in the "Related" links on the right margin of this window mentioned them directly. One was "Android: How to declare global variables?" and the other was "how to pass value betweeen two tab in android". Both pointed to the Application Class as the place to define global variables and methods. Armed with this new knowledge, I found an article called "Android Application Class" on the Xoriant blog that expanded on the StackOverflow answers.
It's best to review those three links first. I need to add some tips to what those authors have said.
Your Application class has to be in its own separate file. (That might be a "duh" to some people, but not to everybody.) Here's a good framework for an example called Something.java:
public class Something extends Application {
// Put application wide (global) variables here
// Constants are final, so they don't have to be private
// But other variables should be declared private;
// use getters/setters to access them
public final boolean FEET = false;
public final boolean METERS = true;
private boolean units = FEET;
#Override
public void onCreate() {
super.onCreate();
// Put any application wide (global) initialization here
}
// Put application wide (global) methods here
public boolean getUnits() {
return units;
}
public void setUnits(boolean whichOne) {
units = whichOne;
}
}
I'm using Eclipse with the ADT plug-in, in Windows XP. Eclipse doesn't always behave properly if you edit XML code directly, so it's best to open AndroidManifest.xml, then select the Application tab and enter your application name in the Name field. You don't need to put a dot or period in front of the name. Just type in the name of your class, like "Globals" or "MyApplication" or whatever. (Note that this is the default application in your Manifest. You don't have to create a separate <application></application> tag.
This step may not be necessary on an actual Android device, but it was necessary for the emulator: you need to use the getApplicationContext() command in every onCreate() and every method that will be accessing the global variables and methods. I tried to put it outside of onCreate() with the rest of my activity wide variables, and it didn't work. Putting it inside every method seems wasteful, but both the emulator and the Android device work fine with it that way. Here's a sample showing how I used it:
public void fooBar() {
// Access to global variables and methods
final Something s = (Something)getApplicationContext();
// ...
// This next line demonstrates both a global method and a global variable
if (s.getUnits() == s.FEET) {
// do something with feet
} else {
// do something with meters instead
}
// ...
}
Those were the only hiccups I encountered. The three references that I have listed, taken together, are otherwise pretty complete.

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
}

Preference Screen as interface for database?

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.

Categories

Resources