I want to make a simple android app to - generate sequential number every time a button is pressed and save it as it is when it is closed. So when I open it next time it starts from there.
In JAVA I got sequential number part figured. But don't know how to save that number upon closing the app.
Just a simple hint could help me find out the rest.
This is my first question here so ignore if you find it too childish.
Thanks!!
There are many ways to do it:
Using saveInstanceState() and onRestoreInstanceState() these are the two android activity life cycle methods to store data at the time of closing your app.
You can use SharedPreferences to save your data. It basically uses a small XML file for storing your data permanently.
You can also use SQLite database for storing data. [But for this purpose it is not preferable.]
Hope it will meet your question.
Use SharedPreference like -
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get your last saved sequential number
num = getMyNumber();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
++num;
saveMyNumber(num);
}
});
......
}
private void saveMyNumber(int num) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("sequencialnum", num);
editor.commit();
}
private int getMyNumber(){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
return sharedPref.getInt("sequencialnum", 0);
}
Related
I am making Spinning wheel for prize, I am able to disable click event after 3 click but unable to enable click in another day, I just want to make user click only 3 times per day and disable click event for that day and only enable in next day
public class MainActivity extends AppCompatActivity implements SpinningWheelView.OnRotationListener<String> {
private SpinningWheelView wheelView;
private TextView rotate,spinCount,spinPoint;
int COUNT=0;
int points=0;
private SharedPreferences mPrefs;
private SharedPreferences.Editor editor;
private String sharedPref="MY_PREF";
int count= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrefs=getSharedPreferences(sharedPref,Context.MODE_PRIVATE);
mPrefs.getInt("count",0);
editor=mPrefs.edit();
wheelView = (SpinningWheelView) findViewById(R.id.wheel);
rotate = (TextView) findViewById(R.id.rotate);
spinCount=(TextView)findViewById(R.id.spin_count);
spinPoint=(TextView)findViewById(R.id.spin_point);
wheelView.setItems(R.array.dummy);
wheelView.setOnRotationListener(this);
rotate.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
int i = mPrefs.getInt("count",0);
if (i<3){
count++;
editor.putInt("count",count);
editor.apply();
wheelView.rotate(80, 3000, 50);
}else {
rotate.setEnabled(false);
//how can it be enabled on another day
}
}
});
}
I can achieve it with Shared Preferences, but Shared Preferences can be cleared by clearing data and cache, which is not good for my app as I want to store their points on the cloud.
Most Simple Solution
isTodayClickable =true/false
OnCreate() get the time stamp and set the clicable true/ clicked and
clicked date Both save in shared pref after 3 click enable it to
false save it in pref write logic if there is shared pref for date
chek if the date is more than one day then set it to true and save it
in pref
but unable to enable click in another day
You can store the date/time of the first click and reset it after 24 hours, or reset at midnight.
this is not recommended as you know, because clients can bypass these kind of limitations easily.
back to the main question
How to limit click event only 3 time per day
1. make a UUID for that client installation:
The Description in google's docs is far beyond good.
2. Add a field in your server's database/table for this UUID's clicks. The UUID is your primary key. increase clicks field after every click. For sending a request this simple to your server, you do not really need a library, but AsyncHttpClient makes it easy.
If the internet is not available, tell your users about it. Do not continue offline since they can easily cheat.
3. store the date/time of that first click in your server.
4. Make a simple stored procedure in your SQL database that resets the dates at 00:00 .
Create date object store in shared preferences with number of button click.
on next day create new date and map with shared preferences stored date.
if match then disable button else enable. here is the example below.
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int clicks = 0;
clicks++;
if (clicks >3){
button.setEnabled(false);
}
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", this.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("clicks", clicks);
editor.putString("date",date.toString());
editor.apply();
}
});
Happy coding!!
I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.
You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}
Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.
In my activity below, I have an integer called test. I want this integer to add 1 to itself every time the activity is opened and then get a toast to display its value. I have done this, but every time I open the activity the value is always printed in the toast as 1. Why is this?
int test = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hangar);
final SharedPreferences saving = getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
final SharedPreferences.Editor editor = saving.edit();
test = saving.getInt("testing", 0);
test++;
Toast.makeText(this, "Hello There " + test, Toast.LENGTH_SHORT).show();
editor.putInt("testing", test);
You are missing commit or apply:
editor.putInt("testing", test);
editor.commit ();
Without it, your changes to SharedPreferences are not persisted.
I want my main activity to show a popup the on launch, this activity is the first activity that is created, but multiple instances of this activity could be created and I only want the first since launch to display this popup, so I would like to know if there how I can check this.
The most simplest way of doing it is use a static variable
How do you use it:
Define a static boolean flag and assign it false value, once the activity is created for the first time, make the flag true, and now you do your task with simple if/else condition
public static boolean flag=false;
then in onCreate
if(flag==true)
{
//Activity is not calling for first time now
}
if(flag==false)
{
//first time calling activity
flag=true;
}
Store flag in SharedPreferences which indicate is application is launched first time or not. Use Activity Oncreate method as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and check SharedPreferences if fist time launch
SharedPreferences settings = getSharedPreferences("showpopup", 0);
SharedPreferences.Editor editor = settings.edit();
if(settings.contains("firsttime")){
// means activity not launched first time
}else{
// means activity launched first time
//store value in SharedPreferences as true
editor.putBoolean("firsttime", true);
editor.commit();
//show popup
}
}
I would use selvins approach. Unless you have a backend to your application setup and user registration, there will be no way for you to get this type of information for a specific application instance unless you use SharedPreferences
int activityLaunchCount = 0;
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPreferences", SharedPreferences.MODE_PRIVATE);
activityLaunchCount = preferences.getInt("ActivityLaunchCount", 0);
if(activityLaunchCount < 1)
{
// ** This is where you would launch you popup **
// ......
// Then you will want to do this:
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Then I would Increment this counter by 1, so if will never popup again.
activityLaunchCount += 1;
// Store the New Value
editor.putInt("ActivityLaunchCount", activityLaunchCount);
// You Must call this to make the changes
editor.commit();
}else{
// If you application is run one time, this will continue to execute each subsequent time.
// TODO: Normal Behavior without showing a popup of some sort before proceeding.
}
Then when you want to Close the application
Override the Activity finish() method
#Override public void finish()
{
super.finish();
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Store the New Value
editor.putInt("ActivityLaunchCount", 0);
// You Must call this to make the changes
editor.commit();
}
im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further