Android Save Spinner Selection - android

I have two activities. In the second activity I have a spinner. what I would like to happen is after the user selects an item from the spinner it will save via actionbar press and on back press which will load the previous activity. Based on my research my activity is supposed to look something like the following below but it's not working what am I doing wrong??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
spin = (Spinner)findViewById(R.id.editspin);
Intent i = this.getIntent();
note = new ArgueItem();
note.setKey(i.getStringExtra("key"));
note.setText(i.getStringExtra("text"));
EditText et = (EditText)findViewById(R.id.argueEdit);
et.setText(note.getText());
et.setSelection(note.getText().length());
}private boolean saveState() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor = prefs.edit();
int daddy = spin.getSelectedItemPosition();
prefEditor.putInt("savedValue",daddy);
prefEditor.commit();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return false;
}
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return;
}else{
saveAndFinish();
}

In your second activity, you have to override the onPause() and. Inside it write the saving process.
protected void onPause(){
super.onPause();
//Include the code which, save the data.
}

You should use a FragmentActivity and add/remove fragments within the same activity.
check these resources:
http://developer.android.com/guide/components/fragments.html
http://www.vogella.com/articles/AndroidFragments/article.html

This is how i'm initializing my spinner which is in the ActionBar. I'm not adding it as a custom view, but I'm using the drop down menu feature.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//save in preferences
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().
putInt(SELECTED_DIARY_PREF, itemPosition).commit();
return true;
}
});
int selPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SELECTED_DIARY_PREF, 0);
actionBar.setSelectedNavigationItem(selPosition);
What this code does is: saving the preference when an item of the menu is clicked, and restoring that preference when the activity is launched. Hope it helps.

Related

How to put score from one activity into another activity without going to that activity?

I am making a game like logo quiz. I have the question activity and the levels activity so when users answer correctly they score 1. Then I want to put the score in the levels activity so in that way users could unlock the next level, but I don't want users leave the question activity and until now I have only found this method:
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.putExtra("score", score);
startActivity(resultIntent);
However, with this method the user goes to the levels activity.
I will leave my code for reference:
public class Big extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_big);
init();
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true); }
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), Level1.class);
startActivityForResult(myIntent, 0);
return true;
}
private Button buttonSaveMem1;
private EditText escrive;
private TextView respuest;
private String [] answers;
int score=0;
int HighScore;
private String saveScore = "HighScore";
private int currentQuestion;
public void init()
{
answers = new String[]{"Big"};
buttonSaveMem1 = (Button)findViewById(R.id.button1);
respuest = (TextView) findViewById(R.id.textView2);
escrive = (EditText) findViewById(R.id.editText1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
checkAnswer();
// TODO Auto-generated method stub
SavePreferences();
LoadPreferences();
}};
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
public void checkAnswer() {
String answer = escrive.getText().toString();
if(isCorrect(answer)) {
update();
respuest.setText("You're right!" + " The Answer is " + answer + " your score is:" + score +" " +
"HighScore: " + HighScore);
score =1;
}
else {
respuest.setText("Sorry, The answer is not right!");
}
}
private void update() {
if (score > HighScore)
{ HighScore = score; }
}
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", respuest.getText().toString());
sharedPreferences.edit().putInt(saveScore, HighScore).commit();
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
HighScore = sharedPreferences.getInt(saveScore, 0);
respuest.setText(strSavedMem1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is the levels activity:
public class Level extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
Button salir = (Button) findViewById(R.id.button3);
salir.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, MainActivity.class)); }
}
)
;
Button leve2 = (Button) findViewById(R.id.button1);
leve2.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level2.class)); }
}
)
; }
Button leve1 = (Button) findViewById(R.id.button1);
leve1.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level1.class)); }
}
)
;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level, menu);
return true;
}
}
Thanks for the help!
In your questions activity, store the score of the user in the SharedPreferences
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
prefs.edit.putLong(USER_SCORE, score).commit();
And then when you return to your level's activity, you can fetch from the preferences.
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
long userScore = prefs.getLong(USER_SCORE, 0);
USER_SCORE is just a string key like USER_SCORE = "user_score" to allow the device to find the date you stored in the prefs.
Shared preferences are saved to the phone and not accessible except through the app that they belong to. So upon starting the app again, you can get the User's score that was saved last time they used the app.
You can make make the score as static and then modify it from the other activity class. IT would automatically change it in the original.
Store the score in a SharedPreferences instead of passing it to Level in an intent. You can then retrieve that score within the levels Activity (or any other for that matter), whenever the user may navigate there. You already use SharedPreferences in your code with:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
However that returns a Shared Preference using the calling Activity's class name as the Shared Preference name, i.e. those preference values are private to your Activity 'Big'. To use preference values that have application scope, use getSharedPreferences(), providing a Shared Preferences name:
SharedPreferences sharedPreferences = getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);
Create an Editor from that and store the value of 'score'. Then retrieve it your Level activity, most likely in its onCreate().
After looking here and there, I've finally found out my answer to this question by following other answers and I basically used the following combination of codes to do so.
In a first activity:
import:
import android.content.Context;
import android.content.SharedPreferences;
declare:
public static int totalCount;
and add onCreate():
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);`
totalCount++;`
editor.putInt("counter", totalCount);`
editor.apply();`
Then, on a second activity:
import:
import static com.example.myapp.totalCount
and add onCreate():
((TextView) findViewById(R.id.text_view_id)).setText(String.valueOf(totalCount));
In the layout for the second activity:
place a TextView with:
android:id="#+id/text_view_id"
And pay attention to what the documentation says about naming shared preferences.
When naming your shared preference files, you should use a name that's
uniquely identifiable to your app. An easy way to do this is prefix
the file name with your application ID. For example:
"com.example.myapp.PREFERENCE_FILE_KEY"

How to check if a user has already clicked a Button?

I have a button in my menu with a “promo code” inside. I need to check if a user already clicked it so I can tell him (the next time he clicks it) “You already redeemed this promo code!” How do I do that? I need only the piece of code where I can check for button clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean clicked = false;
switch (item.getItemId()) {
case R.id.getcode:
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { Button btn = (Button) findViewById(R.id.getcode);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(getString(R.string.congrats) + "\n" + getString(R.string.promcd) + "\n" + "ASC2013-"+Build.ID+"-"+android.os.Build.SERIAL.charAt(3)+"-"+Build.SERIAL.charAt(6)+"-"+Build.SERIAL.charAt(9)+"-"+Build.SERIAL.charAt(12));
dlgAlert.setPositiveButton(R.string.go,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"lorenzocascio#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.validreq)+Build.BOOTLOADER);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.why) + "\n" + getString(R.string.validreq1) +"\n"+getString(R.string.dialogMSG1);
emailIntent.setType("plain/text");
startActivity(emailIntent);
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
break;
}
switch (item.getItemId()) {
case R.id.settings:
Intent settings = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(settings);
}
return true;
}
How about a simple boolean flag?
Set it to false in the beginning - as soon as the user clicks - set it to true.
private boolean clicked = false; // this is a member variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(clicked) {
Toast.makeText(getActivity(), "You already clicked!", 1000).show();
} else {
Toast.makeText(getActivity(), "You clicked for the first time!", 1000).show();
}
clicked = true;
}
}
}
Please be aware that the "clicked" boolean variable must be a member variable of your Activity, otherwise it will not be visible inside onClick(). A variable being a member variable simply means that it belongs to the class it is in, and not just occurs in a specific method. In the above code, "btn" would be a "normal" variable since it only appears inside onCreate() (a method), whereas "clicked" is declared for the Activity (the class it is in), and is therefore a member variable.
If you want to save if the user has clicked even after the app was closed and gets reopened, take a look at the SharedPreferences.
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
boolean clicked;
clicked = prefs.getBoolean("yourkey", false); // get a value, use whatever key you want
prefs.edit().putBoolean("yourkey", clicked).commit(); // save a value, use same key
You can save a flag in shared preferences if the user clicks the button. Next time, you can check in the shared preferences if there exists the flag.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { // User hasn't actived the promocode -> activate it
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
}

OnPreferenceChangeListener

I have a EditText in a preference menu that allows me to edit a URL address. The problem is when I get the preference value in the mainActivity is not getting updated right away after I click OK in the Preference Menu. Not sure how to fix this problem. I tried a bunch of ideas and finally decided to ask.
public class PreferencesActivityTest extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.radio_preferences);
PreferenceManager.setDefaultValues(PreferencesActivityTest.this,
R.xml.radio_preferences, false);
EditTextPreference editPref =(EditTextPreference)findPreference("MyText");
editPref.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() > 0) {
return true;
}
// If now create a message to the user
Toast.makeText(PreferencesActivityTest.this,
"Invalid Input", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
PS: This code updates the newValue to what I enter in the EditTextPreference, doesn't carry the new value to the MainActivity until I modify it again...
UPDATE:
In OnResume() I can see that the value is updated with the one that I modified in the PreferenceActivityTest from EditTextPreference. What I'm trying to do is to pass this newValue into the SetDataSource("").
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_radio);
initializeMediaPlayer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
editURL();
// make a Dialog or show an Activity
return true;
}
}
private void initializeMediaPlayer() {
PreferenceManager.setDefaultValues(this, R.xml.radio_preferences, false);
SharedPreferences pref =PreferenceManager.getDefaultSharedPreferences(this);
String radioPath = pref.getString("MyText", "default value");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
try {
radioPlayer.reset();
// radioPlayer.setDataSource("http://31.xx.xxx");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
radioPlayer.setDataSource(radioPath);
} catch {
}
}
public void editURL() {
stopPlaying();
startActivity(new Intent(getBaseContext(), PreferencesActivityTest.class));
}
I am doing something fundamentally wrong but I need help. Thank you in advance !
how are you calling the preference activity? If you are calling it directly, you probably need to change the call to startActivityForResult so you refresh your data once you return from the Activity

Android : Shared preferences inside tabhost not working

I have a tabhost with three activities and I want to save the pressed state of the buttons of each activity
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other the button pressed state will be reflected on moving back. first activity -> all 4 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state
When I go to second child tab and come to the first child tab the change(The buttons which I pressed are not in pressed state) is not reflecting
Help is always appreciated , Thanks
this is my code in first tabhost child activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seatdirnbtn.setOnClickListener(listner1);
seatdirnbtn1.setOnClickListener(listner2);
seatdirnbtn.setPressed(true);
seatdirnbtn1.setPressed(true);
this.LoadPreferences();
}
private void SavePreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", seatdirnbtn.isEnabled());
editor.putBoolean("state1", seatdirnbtn1.isEnabled());
editor.commit();
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
Boolean state = sharedPreferences.getBoolean("state", false);
Boolean state1 = sharedPreferences.getBoolean("state1", false);
seatdirnbtn.setPressed(state);
seatdirnbtn1.setPressed(state1);
}
#Override
protected void onStart() {
super.onStart();
LoadPreferences();
}
#Override
protected void onPause() {
SavePreferences();
super.onPause();
}
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
isclick = !isclick;
}
};
private View.OnClickListener listner2 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2hlt);
} else {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2);
}
isclick = !isclick;
}
};
probably you should override onResume() method in which you should set buttons states. this method is called after onCreate() and even the activity is already created. If you have activities in tabHost they are not created each time you switch between tabs so onCreate() method will be called only once but onResume() every time you switch to tab with particular activity.
your code which is loading preferences is in onStart() method. Look here on activity lifecycle. You can see that this method is called only if your activity was stopped before but will never called if it was just paused.
EDIT:
if you have just 2 states like in your code from question it could be better to use ToggleButton which also generally have 2 states. You can style it to have different backgrounds for each state. This tutorial could be helpfull.
Than you will have a little bit different Listener:
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(checked) {
//do sth if it's checked
} else {
//do sth if it's not checked;
}
}
});
to change states for them programatically:
toggleButton.setChecked(true); //or false
so finally you can save this state to SharedPreferences:
editor.putBoolean("toggleButton1",toggleButton.isChecked());
and when you will need this state:
boolean isChecked = sharedPreferences.getBoolean("toggleButton1",false);
toggleButton.setChecked(isChecked);
selector will take care of switching button backgrounds for each state.

Android: CheckboxPreferences act like RadioButtons

I have four checkboxpreferences in my preferencescreen that I would like to interact like a radiobuttongroup, meaning that you can only check one of them! If lets say the first is checked, and you like to check another one, its just the desired one checked, and the other ones is unchecked.
I did like this :
public class PreferenceActivity extends PreferenceActivity {
private SharedPreferences prefs;
private Editor editor;
private int keyItemChecked;
private CheckBoxPreference item1CheckBox, item2CheckBox, ..., itemICheckBox;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
addPreferencesFromResource(R.xml.prefs);
item1CheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("item1");
item2CheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("item2");
...
itemICheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("itemI");
item1CheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
manageItem(1, item1CheckBox);
return true;
}
});
....
itemICheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
manageItem(I, itemICheckBox);
return true;
}
});
}
private void manageItem(int i ,CheckBoxPreference pref) {
keyItemChecked = prefs.getInt("keyItemChecked",1); // 1 is your default checked item
if (! pref.isChecked() && keyItemChecked == i)
// If you click on the checked item, you don't want it to be unchecked :
pref.setChecked(true);
if (pref.isChecked() && keyItemChecked != i) {
editor = prefs.edit();
editor.putInt("keyItemChecked", i);
editor.commit(); // or editor.apply() if you use API > 9
unckeckOldItem(keyItemChecked);
}
}
private void unckeckOldItem(int item) {
switch (item) {
case 1:
item1CheckBox.setChecked(false);
break;
...
case I:
itemICheckBox.setChecked(false);
break;
}
}
You don't need to declare "keyItemChecked" on your prefs.xml.
The first time you call the activity, the data doesn't exist and
keyItemChecked = prefs.getInt("keyItemChecked",1);
will return 1.
Once you click on an other item than the default, the data will exist.
Looks like you can use http://developer.android.com/reference/android/preference/CheckBoxPreference.html#setDisableDependentsState%28boolean%29 to create that functionality. I think setting dependency of preferences can be done in xml.

Categories

Resources