I want to disable the upload button for one day for after uploading firebase photo. i tried these codes, countdown works incorrectly when I change activity.
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long currentTime = new Date().getTime();
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", currentTime);
editor.apply();
dwn.setEnabled(false);
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long previousTime = prefs.getLong("time", 0);
long currentTime = new Date().getTime();
if (currentTime - previousTime > 60*1000){
dwn.setEnabled(true);
} else {
dwn.setEnabled(false);
new CountDownTimer(currentTime - previousTime, 1000) {
public void onTick(long millisUntilFinished) {
dwn.setText("fdfjhsn" + millisUntilFinished / 1000);
}
public void onFinish() {
dwn.setEnabled(true);
}
}.start();
This might be more than you were looking for, but I would extract the decision making to a separate class. Consider the following:
interface UserUploadHelper {
void userUploadedImage();
boolean canUserUploadImages();
}
We can have an implementation of this, backed by SharedPreferences. This object can then be injected into wherever we need it:
class SharedPreferencesUserUploadHelper implements UserUploadHelper {
private static final String LAST_IMAGE_UPLOAD_TIME = "last.user.upload.time";
private static final String PREFS_NAME = "user.upload";
private static final String PREFS_MODE = Context.MODE_PRIVATE;
private static final String MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
private final SharedPreferences sharedPreferences;
SharedPreferencesUserUploadHelper(Context context) {
sharedPreferences = context.getSharedPreferences(PREFS_NAME, PREFS_MODE);
}
#Override
void userUploadedImage() {
sharedPreferences.edit().putLong(
LAST_IMAGE_UPLOAD_TIME,
new Date().getTime()
).apply();
}
#Override
boolean canUserUploadImages() {
long lastUploadTime = sharedPreferences.getLong(LAST_IMAGE_UPLOAD_TIME, 0L);
long now = new Date().getTime();
return lastUploatTime - now > MILLIS_IN_DAY;
}
}
Inside your upload code, when the code finishes uploading, you can call userUploadedImage()
Inside your activity code, you can check whether the button should be enabled with canUserUploadImages().
Doing this lets you change how you store that value and calculate the timeout without changing your firebase logic or your view logic.
You can inject this into a class using a tool like Dagger, or simply by creating an instance of it via its constructor. If you want to hide the concrete SharedPreferencesUserUploadHelper implementation, you can use a factory! This is good when you might decide to change how this class is implemented later.
public UserUploadHelperFactory {
public UserUploadHelper create(Context context) {
return new SharedPreferencesUploadHelper();
}
}
If we wanted to go a step further, we would actually break our original interface into two different interfaces, one for each method, since each method has different interested parties, and, for example, the view shouldn't be able to call userUploadedImage (Which makes that original interface a slight violation of the Interface Segregation Principle!)
Related
I have an int variable called mCurrentIndex. I want to do something when its value changes.
For example:
public class MainActivity extends Activity{
private int mCurrentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Apps logic.
}
public onCurrentIndexValueChange(){
button.setClickable(true);
}
}
One approach to solving this is using Android's LiveData.
In your situation, since you'd like to observe an int, you can do something like this:
public MutableLiveData<Integer> mCurrentIndex = new MutableLiveData<>();
To change your value, you would do this:
mCurrentIndex.setValue(12345); // Replace 12345 with your int value.
To observe the changes you would do the following:
mCurrentIndex.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable final Integer newIntValue) {
// Update the UI, in this case, a TextView.
mNameTextView.setText("My new current index is: " + newIntValue);
}
};);
}
This approach is useful because you can define a ViewModel to segregate your logic from your Activity while having the UI observe and reflect the changes that occur.
By separating your logic out to the ViewModel, your logic becomes more easily testable since writing tests for your ViewModel is relatively easier than writing tests for your Activity.
For more information on LiveData check out this link.
you can use a setter function
private int mCurrentIndex = 1;
public void setCurrentIndex(int newValueFormCurrentIndex)
{
if(newValueFormCurrentIndex != mCurrentIndex)
{
onCurrentIndexValueChange();
mCurrentIndex = newValueFormCurrentIndex;
}
}
If the scope on mCurrentIndex is only in MainActivity then I think it would be best just to create getter and setter methods for mCurrentIndex and at the end of the setter method call onCurrentIndexValueChange()
public int getIndex(){
return this.mCurrentIndex;
}
public void setIndex(int value){
this.mCurrentIndex = value;
this.onCurrentIndexValueChange();
}
I have a wicket application on a page we have various forms for the same model split into separate tabs. What I need to do is whenever a tab is clicked check to see if a js variable tabDirty is set to true or false. If it is true I would launch a confirm prompt if okay then reset that form and move to the clicked tab. If cancel stay on that tab with keeping current changes.
I have this js for the warning nothing fancy
function warnOnChange(){
if(tabDirty){
decision = confirm('Leave?');
if(decision){
resetTab(); //sets tabDirty back to false
} else {
return false;
}
}
}
I have a super simple wicket behavior
public class WarnChangePromptOnClickBehavior extends Behavior {
#Override
public void bind(Component component) {
component.add(JQBehaviors.mouseClick(EditMerchant.WARN_ON_CHANGE));
}
}
and that behavior is added to the AjaxFallBackLink
AjaxTabbedPanel<CustomAjaxTab> tabbedPanel = new AjaxTabbedPanel<CustomAjaxTab>("tabbedPanel", tabList, new Model<>(0)) {
private static final long serialVersionUID = 1L;
#Override
protected WebMarkupContainer newLink(final String linkId, final int index) {
AjaxFallbackLink<Void> link = new AjaxFallbackLink<Void>(linkId) {
private static final long serialVersionUID = 1L;
#Override
public void onClick(final AjaxRequestTarget target) {
TabbedPanel<CustomAjaxTab> selectedTab = setSelectedTab(index);
CustomAjaxTab tab = tabList.get(index);
if (target != null) {
tab.getPanel(linkId);
target.add(selectedTab);
}
onAjaxUpdate(target);
}
};
link.add(new WarnChangePromptOnClickBehavior());
return link;
}
};
Current behavior with this is that if there is no change the tabs switch no prompt. If there is a change then I get the prompt. If okay tabDirty is reset and go to the next page clearing changes. Issue is that if I click cancel I still navigate to the next tab and lose changes. I know there is something in onClick I need to change but it is just not registering with me.
It is not that easy to intercept the JS event loop, especially when using Ajax requests.
Here is an approach that may do the job:
In warnOnChange() if dirty then call event.preventDefault() and event.stopImmediatePropagation(). This will tell the browser to not follow the link / make an Ajax call. Then show the confirmation dialog as you do now.
If the user presses Cancel then there is nothing more to do
If the use confirms then set dirty to false and do jQuery(event.target).triggerHandler(event.type), i.e. execute the same event (click) on the link. This time it won't be dirty and it will proceed with the Ajax call.
Not sure if this is the appropriate way to do this but I solved my issue like this:
Same old js just slightly modified to return what the user chose:
function warnOnChange(){
decision = true;
if(tabDirty){
decision = confirm('Leave?');
if(decision){
resetTab();
}
}
return decision;
}
Dumped the whole behavior code although I still think it could be used just not sure at the moment...
So to make this all work on the link I override the updateAjaxAttributesof the link with a precondition:
AjaxTabbedPanel<CustomAjaxTab> tabbedPanel = new AjaxTabbedPanel<CustomAjaxTab>("tabbedPanel", tabList, new Model<>(0)) {
private static final long serialVersionUID = 1L;
#Override
protected WebMarkupContainer newLink(final String linkId, final int index) {
AjaxFallbackLink<Void> link = new AjaxFallbackLink<Void>(linkId) {
private static final long serialVersionUID = 1L;
#Override
protected void updateAjaxAttributes( AjaxRequestAttributes attributes ) {
super.updateAjaxAttributes( attributes );
AjaxCallListener ajaxCallListener = new AjaxCallListener();
//very important to use the "return" if not then nothing happens with the response
ajaxCallListener.onPrecondition("return " + WARN_ON_CHANGE);
attributes.getAjaxCallListeners().add( ajaxCallListener );
}
#Override
public void onClick(final AjaxRequestTarget target) {
TabbedPanel<CustomAjaxTab> selectedTab = setSelectedTab(index);
CustomAjaxTab tab = tabList.get(index);
if (target != null) {
tab.getPanel(linkId);
target.add(selectedTab);
}
onAjaxUpdate(target);
}
};
link.add(new WarnChangePromptOnClickBehavior());
return link;
}
};
Hello guys i have a question.
I have a button with 2 options like checked and unchecked for girl and i have same for boys. In my fragment i need to select one and save it in SharedPreferences.
i have this for configure buttons:
private void setSexButtons() {
sexButtonBoy.setOnClickListener(view -> {
sexButtonBoy.setSelected(true);
sexButtonBoy.setScaleX(1.4f);
sexButtonBoy.setScaleX(1.4f);
sexButtonGirl.setSelected(false);
sexButtonGirl.setScaleY(1.0f);
sexButtonGirl.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
sexButtonGirl.setOnClickListener(view -> {
sexButtonBoy.setSelected(false);
sexButtonGirl.setSelected(true);
sexButtonGirl.setScaleX(1.4f);
sexButtonGirl.setScaleX(1.4f);
sexButtonBoy.setScaleY(1.0f);
sexButtonBoy.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
}
and i also have a method to save - but i think i do something bad becouse this not work
public static void setSelectedIem(boolean selectedIem) {
getPreferences().edit()
.putBoolean(SELECTED_SEX, selectedIem)
.apply();
}
private static final String SELECTED_SEX = "selectedSex";
Please give me any advice how to do this good.
Sorry i miss it here is it:
privated SharedPreferences sharedPreferences;
and in onCreate
sharedPreferences = getSharedPreferences("me.fast.app", MODE_PRIVATE);
and here is main method:
private static SharedPreferences getPreferences() {
return ApplicationFast.sharedPreferences;
}
Updated with new method
public static boolean isSelectedItem(){
return getPreferences().getBoolean(SELECTED_SEX, false);
}
I think your problem is saving a boolean, because for both sexes you are saving "true".
You should do this:
private void setSexButtons() {
//If you want to recover the settings do this:
sexButtonBoy.setSelected(Settings.isSelected());
sexButtonGirl.setSelected(!Settings.isSelected());
sexButtonBoy.setOnClickListener(view -> {
sexButtonBoy.setSelected(true);
sexButtonBoy.setScaleX(1.4f);
sexButtonBoy.setScaleX(1.4f);
sexButtonGirl.setSelected(false);
sexButtonGirl.setScaleY(1.0f);
sexButtonGirl.setScaleX(1.0f);
Settings.setSelectedIem(true);
});
sexButtonGirl.setOnClickListener(view -> {
sexButtonBoy.setSelected(false);
sexButtonGirl.setSelected(true);
sexButtonGirl.setScaleX(1.4f);
sexButtonGirl.setScaleX(1.4f);
sexButtonBoy.setScaleY(1.0f);
sexButtonBoy.setScaleX(1.0f);
Settings.setSelectedIem(false);
});
}
And then:
public static void setSelectedIem(boolean selectedIem) {
getPreferences().edit()
.putBoolean(IS_BOY, selectedIem)
.apply();
}
private static final String IS_BOY = "isboy";
How can I check whether a boolean is true or false from another java class?
menu.class
public class menu extends AppCompatActivity {
TextView textPoints;
Button button2;
public boolean easy;
public void Click(View v) {
if (button2.getText().equals("Svårighetsgrad: Svårt")) {
easy = true;
button2.setText("Svårighetsgrad: Lätt");
}
else {
easy = false;
button2.setText("Svårighetsgrad: Svårt");
GameActivity.class
menu m = new menu();
if (m.easy == true) {
myImageView.setVisibility(View.VISIBLE);
newAndroid();
points = getPoints() - 1;
text1.setText("Poäng: " + points);
}
else {
myImageView.setVisibility(View.VISIBLE);
newAndroid();
points = getPoints() - 5;
text1.setText("Poäng: " + points);
you are developing for Android right?
you should probably use SharedPreference in this case (it would be easier).
use this code to save value:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("EASY", easy);
editor.commit();
and this code to get the value:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean score = sharedPref.getBoolean("EASY", defaultValue);
If you're just trying to get whether or not a value is true or false, you could either make your boolean public or you could make a getter method.
public boolean getBooleanValue(){
return booleanYouWant;
}
You need a reference on that class in order to do that. The common way of communicating would be the observer pattern for java. Delegation is also a possibility - which will create a double reference, but in Java you usually want to take observer pattern, as it is implemented by default.
You can also have some kind of singleton pattern, to have a global reference of an instance.
Basically my question is I want to set lets say a string to A or B that is chosen by the user on the first screen. And then have this string variable be saved to be used on other actives else where in the app. I have see the posts and many like in Android global variable.
But the variable needs to be set and the gotten on each activity the variable isn't saved, once and then can be used everywhere?
How could this be done?
I hope i have explained this well enough, as my question differs from the one above.
The variable is not final it can be changed on the first activity but then I want to use it on the following activities, with out having to pass it with intent to each one.
Thanks for the help in advance.
You can use a public class with static String variable or passing the variable to another Activity with putExtra method.
Example :
public class Global {
public static final String DEVELOPER_KEY;
public static final String PLAYLIST_ID;
}
I have made one class for same purpose :
public class Constant {
public static int NUMBER_OF_TILES;
public static String setTilesId[] = {};
public static String TilesDesc[] = {};
public static String Image[] = {};
public static String TilesName;
public static int numberofbox = 0;
public static boolean isLogedIn = false;
public static String TilesSize = null;
public static boolean from_activity = true;
public static String URL_FOR_PRODUCT_ACTIVITY;
}
Now i can use this variables from anywhere in my APP.
You can put your variable in SharedPreferences. As it exactly matches you requirement.
You can put your variable in first screen and use it anywhere in your application. Also it is not final, you can change whenever you want it will just overwrite existing value of variable.
And MOST important thing is it will be preserved even after application is closed.
So whenever user starts your application next time you can use that variable.
A.java code:
package p2;
public class A{
public static String abc;
}
After declaring the static string in class A use it anywhere in the package using the class name as it is static so value will remain whatever you update it to.
B.java code :
package p1;
public class B{
public void methodTest(){
String s = A.abc;
}
}
Make your string public static
Ex:public static String myvar="hey"//This will be available across all classes
Instead of using static variable You can simply use Shared Preferences because after some time when your application is in background your static value become free automatically by garbage collector and become null
public void setString(Context context, String value) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getString", value);
editor.commit();
}
public String getString(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
String value = prefs.getString("getString", null);
return value;
}
You can also usw SharedPreferences:
SharedPreferences sets =getSharedPreferences(Choose_a_name, 0);
SharedPreferences.Editor editor=sets.edit();
editor.put string("from user", your string);
editor.commit();
And in your other activities you can retrieve, change and save them again. In that way, you can provide the customized data from the user over the activity lifecycle. Even If your task is completely killed, your data is available on the next launch.
To retrieve the data from another activity:
SharedPreferences sets = getSharedPreferences(yourPrefName,0);
String your string = sets.get string("from user", default value);
I want to give you alternative ideas comparing to intents or static classes. Hope it helps :)
class SharedPref
{
public void setString(Context context, String value) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getString", value);
editor.commit();
}
public String getString(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setString",
0);
String value = prefs.getString("getString", null);
return value;
}
}
and use this class like
SharePref pref=new SharedPref();
pref.setString("Hellooo");
String value=pref.getString();