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();
}
}
Related
I am using SingleChoiceItems in ActionBar using DialogBuilder. I need to save the item selected even after exiting the application then restore the saved setting when accessing the application again.
I saw many examples of shared preferences and onRestoreInstanceState() and onSaveInstanceState() but I am quite confused. Below is the code with explanations of what I did.
Dialog Builder
I saved the present state of the selected option in - > selectPosition .. Then saving the selectedPosition in the global variable isChecked and setting it to the SelectSingleChoice arguments.
public void displaySortDialog(final Context context) {
int selection = context.getSharedPreferences(PREF_NAME,
Context.MODE_MULTI_PROCESS).getInt("Selection_key", 0);
Toast.makeText(getApplicationContext(), "Start Sel :"+selection , Toast.LENGTH_SHORT).show();
CharSequence[] sort_options = { "Z-A", "A-Z", "Size" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.sort_apps));
builder.setSingleChoiceItems(sort_options, selection,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int selected_sort) {
/*
* Toast.makeText(getApplicationContext(),
* sort_options[selected_sort], Toast.LENGTH_SHORT)
* .show(); // isChecked = restoredChecked;
*/
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// saving
context.getSharedPreferences(PREF_NAME,
Context.MODE_MULTI_PROCESS).edit()
.putInt("Selection_key", id ).commit();
Toast.makeText(getApplicationContext(), "Choosen :"+id, Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
Declaring and using the displaySortDialog funtion
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
result = menuChoice(item);
switch (item.getItemId()) {
case R.id.menu_Sort_By_Size: {
displaySortDialog(getBaseContext());
break;
}
case R.id.menu_Action_Search: {
// openSearch();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
Using the below code when I long press the home button or press the home button from the application the selected setting seems OK. They are selected and saved as I toast the message to make sure they are selected which means onSaveInstanceState is working because the toast message in onSaveInstanceState is displayed. But when I try to restore the settings saved through onRestoreInstanceState() then it doesn't work. After exiting the application the settings go back to default.
public void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState != null){
isChecked = savedInstanceState.getInt("SELECTED_SORT_ITEM");
Toast.makeText(getApplicationContext(), "RESTORED: "+isChecked, Toast.LENGTH_SHORT).show();
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
//outState.putInt(SELECTED_SORT_ITEM, getActionBar().getSelectedNavigationIndex());
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(SELECTED_SORT_ITEM, isChecked);
Toast.makeText(getApplicationContext(), SELECTED_SORT_ITEM+isChecked, Toast.LENGTH_SHORT).show();
}
The toast OnSaveInstanceRestore is shown when I press the home button from the app or long press the home button and again select the app. But after exiting the app I am unable to restore the selected settings.
If you can help me with these methods or know some other method it would be appreciated.
Use shared preference,
like:
// For saving
context.getSharedPreferences(PREF_NAME,Context.MODE_MULTI_PROCESS)
.edit()
.put("Selection_key",selectedPosition)
.commit();
//For retrieve
int selection = context.getSharedPreferences(PREF_NAME,Context.MODE_MULTI_PROCESS)
.getInt("Selection_key",0); // 0 being default selection value, put whatever u want
// int selection, Use this Selection for your UI
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"
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.
I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()
I am currently developing an android game and I have an options screen which at the moment has one Option in the form of a ToggleButton: Music on, or Music off.
I currently have this boolean in place, so the class checks if the music is currently playing and then this determines if the ToggleButton is checked or not:
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
So now I want to be able to send the values of True or False to a SQLite database I have set up. At this current moment in time, the only way I can do this is creating a TextView which changes value whether the ToggleButton is checked or not. The value in the TextView is then sent to the database successfully, but this creates problems such as not saving the current settings selected by the user.
Thank you to anyone who replies, if you require anymore code to help you answer I will supply it asap.
I have found some of the answers to be quite confusing, so I think it would be best if I just copied all of my code to here so you can get a better understanding:
public class OptionsActivity extends Activity {
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
final TextView tSound = (TextView) findViewById(R.id.textView2);
final TextView tJoin = (TextView) findViewById(R.id.textView3);
final Button saveBtn = (Button) findViewById(R.id.optSaveBtn);
final Button tblBtn = (Button) findViewById(R.id.tableBtn);
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
final ToggleButton joinOption = (ToggleButton) findViewById(R.id.joinPref);
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
boolean joinChecking = joinOption.isChecked();
soundOption.setChecked(musicPlays);
if(musicPlays==true){
tSound.setText("On");
}
if(musicPlays==false) {
tSound.setText("Off");
}
if(joinChecking==true){
tJoin.setText("Auto");
}
if(joinChecking==false){
tJoin.setText("Manual");
}
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if(soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
}
else {
if(stopService(i)==true){
soundOption.setChecked(false);
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
}
}
}});
joinOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(joinOption.isChecked()){
Toast.makeText(OptionsActivity.this, "Auto", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(OptionsActivity.this, "Manual", Toast.LENGTH_SHORT).show();
}
}
});
tblBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shmoo = new Intent(OptionsActivity.this, SQLView.class);
startActivity(shmoo);
}
});
saveBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()){
case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button".
boolean optionsWork = true;
try{
String sound = tSound.getText().toString();
String join = tJoin.getText().toString();
optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game
entry.open();
entry.createOptionEntry(join, sound); //Passing both strings
entry.close();
}catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database.
Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
finally { //Creating an AlertDialog box when the user presses the Submit button.
if (optionsWork){
Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
});
}
protected void onDestroy() {
if (this.isFinishing()){
super.onDestroy();
stopService(i);
}
}
}
SQLite doesn't handle a boolean type. I always just use smallint and put either a 1 or a 0 in the field. make sure you set it to not accept nulls, and set the default value to either 1 or 0, given your usecase.
here's an example:
CREATE TABLE "db"."boolean_example" ("boolean_example_field" smallint NOT NULL DEFAULT 0);
To store preferences better idea probably will be use Shared Preferences.
And here is example:
SharedPreferences settings = getSharedPreferences("GameSettings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("EnableMusic", mSilentMode);
editor.commit();
...
boolean isOn = settings.getBoolean("EnableMusic",true);