I'M doing quiz app. I have set 50 questions and each question contains 4 options(radio group) with pervious and next button. What i need is when select the answer and goes for next question and again he comes to previous question that time what he select perviously that answer should be in selected state.
But user selected value i getText()
How to implement this ? Any one help me..
Thanks in advance..
ImageView previousbtn1 = (ImageView) findViewById(R.id.prv_btn);
previousbtn1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
if ( j < 1 )
{
Toast.makeText(Question.this, "First Question", Toast.LENGTH_SHORT).show();
}
else
{
--j;
--num;
--m;
TextView txtque = (TextView) findViewById(R.id.que_txt);
txtque.setText("Q" + num + ")" + ques1.get(j));
--k;
btn_practice1.setText(answ1.get((k * 4) + 0));
btn_practice2.setText(answ1.get((k * 4) + 1));
btn_practice3.setText(answ1.get((k * 4) + 2));
btn_practice4.setText(answ1.get((k * 4) + 3));
}
}
});
use SharedPreferences, that will save your values permanently, untill user reinstall (clear data) application. Shared Preferences works like this
// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", string); // here string is the value you want to save
editor.commit();
// restore string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");
Basically it looks like your problem is not how to set a radio button active, but the whole concept - so I describe how I'd do it:
The easy way
Use any kind of list or map (preferably hashmap, where the key is the question number and the value is the answer value (1,2 or 3 - simple integers)). Then when you're at question 2 for example, you check if there is alrerady an entry for the key 2, if so you you read out the value and actviate the corresponding radio button (this is by the way done with radio1.setChecked(true)) - if not as soon as the user clicks a radio button the anser is stored in the hash map.
The maybe better way :)
Almost same as before, but instead of simple "ints" as answers you use objects for your answers (maybe also for the questions, then you could store your answers directly in the question) - this is good if the answers / questions are gonna be more complicated then simple "1,2 or 3".
Side note
If the answers of the users should be available AFTER the app is closed, you'd have to store them in either a sqlite db or in shared preferences. I think sqlite is better for this, since these ansers are not really SharedPreferences/Settings, but you surely need a little more effort.
Since you ask for it:
switch(answer){
case 1:
radio1.setChecked(true)
break;
case 2:
radio2.setChecked(true)
break;
case 3:
radio3.setChecked(true)
break;
default:
break;
}
Related
I'm wanting to store a number of different user favorites (in this example a max of 5) in sharedpreferences.
The user will be able to add and delete these favorites from within the app.
I'm having trouble getting my head around how to achieve this (I assume some sort of looping is needed).
The gist of what I'm trying to do when a user adds a new favorite:
//init prefs
public static final String PREFS_NAME = "PREFS";
SharedPreferences sharedPreferences = null;
SharedPreferences.Editor sharedPreferencesEditor;
//onCreate
sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//method called when user adds new favorite
public void addFavorite(String fav) {
//int i = 0;
//int maxFavs = 5;
//check how many favorites are already stored in shared prefs, if any (is it under maxFavs?)
//if over maxFavs, display error
Toast.makeText(getApplicationContext(),"Favorite added",Toast.LENGTH_SHORT).show();
//else continue
//upon finding available favorite 'space' (less than permitted maxFavs), add to favorites in shared prefs
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString("fav_" + i, fav);
sharedPreferencesEditor.apply();
}
Am I getting the right idea here, or is there a better way to do what I'm intending to do? Hopefully it's clear from the above.
Store favorite count in preferences as an int and read & update it as needed. Also it would be better if you store favorites in preferences as (key : favoritedItemId, value boolean)
Even better: Use a proper local database for situations like this. Preferences is a primitive key value type storage intended for simplier cases like storing a users light mode preference.
Gave up and created a simple database following the example here:
https://inducesmile.com/android/android-sqlite-database-example-tutorial/
Still, if anyone has a solution I'd be interested to see!
This question gets thrown around here a lot. However, my side of the implementation is buggy, so it would help if you guys can help me out. Thanks in advance. Sorry if this question is so noob-like.
I develop Court Counter, which can be found here. I recently started to add saving support for my app. However, I'm not sure if I'm doing it correctly. All other stack overflow topics mention Editor, however Android Studio corrects me to SharedPreferences.Editor. I'm assuming this changed as of Marshmallow or whatever.
Anyway, I added these lines of code for saving and loading:
/**
* Saves your current session
* SharedPreferences key = courtCounter
* team A key = teamA
* team B key = teamB
*/
public void saveSession(View v) {
//We will get saved preferences!
SharedPreferences prefs = this.getSharedPreferences("courtCounter", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("teamA",scoreA);
editor.putInt("teamB",scoreB);
editor.commit();
}
/**
* Loads previous session
* The config is same as saveSession
*/
public void loadSession(View v) {
//We will get the preferences!
SharedPreferences prefs = this.getSharedPreferences("courtCounter", Context.MODE_PRIVATE);
scoreA = prefs.getInt("teamA", 0);
scoreB = prefs.getInt("teamB", 0);
}
saveSession is called when the score gets updated, which you can see below:
/**
* New way of adding score
*
* #param score Score that you need to add to the team
* #param team Team that you want the score added to
* #param last Last clicked item, for example, a1. This will be used for the undo action.
*/
public void scoreAdd(int score, char team, String last) {
Button undo = (Button) findViewById(R.id.undo_button);
undo.setEnabled(true);
lastClicked = last;
if (team == 'a') {
scoreA += score;
displayScore(scoreA, 'a');
}
if (team == 'b') {
scoreB += score;
displayScore(scoreB, 'b');
}
saveSession();
}
However, this throws an error, saying that I didn't supply a (view) or whatever in the brackets. How can I fix this? I don't need any input handlers, but Android Studio would freak out if I didn't make one.
Right now, the code works fine over here:
public void resetAll(View view) {
Button undo = (Button) findViewById(R.id.undo_button);
undo.setEnabled(false);
lastClicked = "reset";
scoreA = 0;
scoreB = 0;
displayScore(scoreA, 'a');
displayScore(scoreB, 'b');
saveSession(view);
}
I'm assuming this is because the resetAll has a view input parameter. However, resetAll is called from an onClick.
Other places where code does not work include the onCreate.
Any ideas?
Your saveSession is not even using the View v within the method, why are you making it as a parameter? Remove it.
public void saveSession() {
...
}
public void resetAll(View view) {
...
saveSession(); // I remove the view here.
}
You have a lot of unnecessary params, unnecessary since your method doesn't even use it.
I already know how to disable the button by using this code:
b.setFocusable(false);
b.setEnable(false);
I want to disable the button once it is clicked for the day, then enable the button the next day in android. In other words, if the button is clicked once today, it will become disabled until tomorrow. Any ideas?
Saving a timestamp in SharedPreferences should suffice. If you're worried about security, you could use a crypto library (see this SO link) and save the datetime in a file, but that is most likely overkill.
To use the SharedPreferences with Dates, it it easy enough to use a formatted string (with day-precision) of a java.util.Date object.
For example, to persist a java.util.Date class to SharedPreferences as a formatted string:
//pre-condition: variable "context" is already defined as the Context object in this scope
String dateString = DateFormat.format("MM/dd/yyyy", new Date((new Date()).getTime())).toString();
SharedPreferences sp = context.getSharedPreferences("<your-app-id>", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("<your-datetime-label>", dateString);
editor.commit();
To retrieve the dateTime again from SharedPreferences, you could try:
//pre-condition: variable "context" is already defined as the Context object in this scope
SharedPreferences sp = context.getSharedPreferences("<your-app-id>", Context.MODE_PRIVATE);
String savedDateTime = sp.getString("<your-datetime-label>", "");
if ("".equals(savedDateTime)) {
//no previous datetime was saved (allow button click)
//(don't forget to persist datestring when button is clicked)
} else {
String dateStringNow = DateFormat.format("MM/dd/yyyy", new Date((new Date()).getTime())).toString();
//compare savedDateTime with today's datetime (dateStringNow), and act accordingly
if(savedDateTime.equals(dateStringNow){
//same date; disable button
} else {
//different date; allow button click
}
}
This makes it rather simple to persist dates and check them again.
You could also store the System's timeInMillis, and use a long value in shared preferences instead of a string representation of the date.
When the button is pressed, you can save the current time into SharedPreferences. One way of gathering the current time would be to use System.currentTimeMillis.
Then during onResume of your activity or after an interval of a custom timer, you could get the stored time from the Shared preferences, subtract it from the current time and then see if that number if larger than a day.
if (now - storedTime > DateUtils. DAY_IN_MILLIS) {
b.setEnabled(true);
}
When the button is pressed for the first time, you need to persist the dateTime somewhere.
When pressed again, you compared the stored dateTime with the actual one.
The way to persist that data is up to you.
I'm making a settings screen using an int to set the background of my app. It works just fine... inside the current activity. But as soon as I leave the activity, the int value is lost and the background isn't changed.
what I want to do: I want to save the int from my settings activity, and then import it to my other activites and check if the int "bak" equals null, "bg", "bg1" or "bg2".
I've heard of sharedPreferences but never got it working. That is why I open a new thread.
OK, add these global variables
SharedPreferences data;
public static String filename = "whateveryou want";
initialize it in onCreate
data = getSharedPreferences(filename, 0);
then to add something to it, use this, with "key" being a unique descriptor and name being the variable name you want to store
SharedPreferences.Editor editor = data.edit();
editor.putInt("key", name);
editor.commit();
access it by this, where default is what you want the variable to be assigned if no preference exists.
intVariable = data.getInt("key", default);
EDIT:
I noticed you want to use letters, eg bg1 etc. To do that you need to use a String, or use an int with a switch case or multiple if statements. Here's a switch case example you can modify. Just make sure to put the switch case statement after you access the SharedPreference in the previous code block.
switch (integerVariable){
case 1: // if the intagerVariable = 1, notice the : not a ;
// set background to BG1
break;
case 2: // if the intagerVariable = 2, notice the : not a ;
// set background to BG2
break;
}
Just add as many case statements as needed.
I have been making a live wallpaper and have finally succeeded so far, but now I would like to let the users choose the background they would like to have that I have in the drawable folder.
I have been trying a few things but so far no luck passing this through.
I have an xml file to read one of two images they can choose from (I figure if I can get one working they all should be the same)
Here's how it reads so far
"DarkBack"
"MediumBackb"
"LightBack"
<string-array name="frontleft_value">
<item>"1"</item>
<item>"2"</item>
<item>"3"</item>
</string-array>bubble
So they choose from either one of three backgrounds
In the activity I have this:
mPrefs = UnderwaterActivity.this.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
myOtherClass.myfrontleftimage = (Integer.parseInt(prefs.getString("front_sub_left_choice", "1")));
}
So this should get me a integer of 1 or 2 depending on which one is click in the settings of the livewallpaper.
The background image is held in a different class but first I have to compare what they clicked, so I tried an if/else statement to no luck at all.
I tried strings but that didn't work so I changed it to int and had some luck but not all.
The if else went like this.
private int chooseImage(){
int theImage = 0;
if(myfrontleftimage == 1){
theImage = R.drawable.image1;
}else if (myfrontleftimage == 2){
theImage = R.drawable.image2;
}else{
theImage = R.drawable.image3;
}
return theImage;
}
Then I put this method into the background image so it can read it, I have a setting java file and implement the engine for shared preferences also but I have a feeling it's in my if else statement, what I want is to get the value of the preference and compare them if they equal to 1, 2, 3 if either one equals one of them then it loads that background image, makes sense in theory but not in practice obviously, any help would be greatly appreciated, if I can figure this one out then I can use it for sprites also that I have in the livewallpaper.
Thanks in advance
EDIT:
I found the issue so far, I put in the pref file this:
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>0x7f020000</item>
<item>0x7f020001</item>
</string-array>
Then in the sharedpreferences file I try to parse the 0x7f020000 (which I want to use to pick the image with) into an int like so
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key)
{
sackNum = Integer.parseInt(prefs.getString("livewallpaper_back", "0x7f020000"));
}
But then I get this error that it can't be done
E/AndroidRuntime(340): java.lang.NumberFormatException: unable to parse '0x7f020000' as integer
So this is where I am stuck at the moment.
I checked the log and the array does get passed through and changes no problem so this is where the issue lies and if anyone can help me parse this thing into an int I would greatly appreciate it.
Thanks again for any help in advance.
You are listening for Shared preference changes, but you do not appear to be setting them.
Set the charedPreferences using and Editor when the user makes a selection.
Then in your activity, read the shared preference in the onCreate() method. That way it will check the savedPreference every time the activity starts.
The code for editing preferences is something like this:
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "MyNameIsBob");
editor.putString("password", "MyPasswordIsEasy");
editor.commit();
}
In your onCreate you would do something like this:
// Get any existing username and password saved
// Restore preferences
SharedPreferences settings = getSharedPreferences("YOURPREFERENCENAME", 0);
user_name = settings.getString("name", "defaultNameValue");
password = settings.getString("password", "defaultPasswordValue");
Ok I figured this out with the help of the test pattern example found here: http://www.codeproject.com/KB/android/AndroidLiveWallpaper.aspx
First I add a third depth to the array.xml like
<string-array name="livewallpaper_back_names">
<item>Brown</item>
<item>Grey</item>
</string-array>
<string-array name="livewallpaper_back_value">
<item>brown</item>
<item>grey</item>
</string-array>
<integer-array name="brownback">
<item>0x7f020000</item>
</integer-array>
<integer-array name="greyback">
<item>0x7f020001</item>
</integer-array>
So now it will read the brown or grey then I add the getResources().getIdentifier to get which array the user picks in the settings menu of the livewallpaper like so:
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
{
String blah;
sackNum = prefs.getString("livewallpaper_back", "brown");
int pid = getResources().getIdentifier(sackNum + "back", "array", getPackageName());
int backImageArray[] = getResources().getIntArray(pid);
int back = backImageArray[0];
int theBackImage = back;
blah = getString(back);
Log.d(TAG, blah);
}
the int pid gathers the array of either brown or grey by adding back (in the xml) and gets the array which I then put into the backImageArray choosing only the first one because thats the only one, next I change the array into an integer (int back = backImageArray[0];) so it can be read to get the image the user chooses which would be theBackImage or you caould just drop it right into the Bitmap as such
private Bitmap _backgroundImage = BitmapFactory.decodeResource(getResources(),theBackImage);
and presto it gets the image. If anyone has a better way of doing this please add to this but so far this works, Mind you you have to update in the code so it reads it and changes it right away but this is the answer I figured out to get the user to at least choose the image.
Hope it helps someone else out.
Sam