How to use shared Preferences in static method - java

here this is my static method
public static void messageHandler(final MessageMO messageMo) {
UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
public void run() {
// SharedPreferences sharedPreferences1;
Log.e("messageHandler", messageMo.getEventTitle());
ChatMO chatMO = new ChatMO();
chatMO.setMessage(messageMo.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMo.getfromUserName());
chatMO.setDate(messageMo.getDate());
chatMO.setEvent_id(messageMo.getEventId());
Log.e("handler", "eventid" + chatMO.getEvent_id());
Log.e("handler", "date" + chatMO.getDate());
listChatMessageObjectses.add(chatMO);
Log.e("handler", "listmessage" + listChatMessageObjectses);
}
});
}
here i have to store the value of listChatMessageObjects into shared preferences how to do it thanks in advance

You will need to change the method signature to receive a Context:
public static void messageHandler(final Context context, final MessageMO messageMo)
And then open the preferences using Context.getSharedPreferences.
PS: listChatMessageObjects sounds like a lot of data.. consider to use a ContentProvider for storing a lot of records.

Related

How to disable button for one day

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!)

How to image button to SharedPreferences and save it

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";

Java: saved settings with Preferences not restored when a GUI application starts

In my Java app, I have a number of saved values and settings that I would like to get as soon as the application starts. All these values are supposed to be stored in a singleton.
For example, I have a JDialog, where I save a path to my file using this:
AppSingleton appSingleton = AppSingleton.getInstance( );
private Preferences prefs;
private void btnSetPanelSetNavdataActionPerformed(java.awt.event.ActionEvent evt) {
appSingleton.setNavdataPath(txtNavdataPath.getText());
prefs = Preferences.userRoot().node(this.getClass().getName());
prefs.put("NAVDATA_PATH", txtNavdataPath.getText());
dispose();
}
I am checking and the value is saved.
This is my singleton:
public class AppSingleton
{
private static AppSingleton instance = null;
private String navdataPath = "";
private AppSingleton()
{
}
public static AppSingleton getInstance()
{
if(instance == null)
{
instance = new AppSingleton();
}
return instance;
}
public String getNavdataPath() {
return navdataPath;
}
public void setNavdataPath(String navdataPath) {
this.navdataPath = navdataPath;
}
public void initDefaultValues()
{
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
this.navdataPath = prefs.get("NAVDATA_PATH","");
System.out.printf("CHECK DEFAULT: %s",this.navdataPath);
}
}
I am trying to get the saved values from the main() method in the class that initializes the JFrame:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run() {
new IGAMainFrame().setVisible(true);
/* HERE!!! */
AppSingleton appSingleton = AppSingleton.getInstance();
appSingleton.initDefaultValues();
}
});
}
But the values are not initialized from the Preference class. "CHECK DEFAULT" shows empty string. I do not understand why and whether there is a better practice of restoring all saved values when a GUI application starts.
Thanks!
Change the line prefs = Preferences.userRoot().node(this.getClass().getName()); inside btnSetPanelSetNavdataActionPerformed to prefs = Preferences.userRoot().node(Appsingleton.class.getName()); Inside button click method, this.getClass() is not AppSingleton

Android - Set variable once and use everywhere in app

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();

How to execute a non static method from a static method

I am new to android/java development so I'm having a few issues, this is one of them.
I want to use the result returned in recevieResults in getTickets. I tried to make getTickets static but it has
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
and so the method being Static doesn't allow for getApplicationContext.
public static void receiveResults(String result2) {
usersXML = result2;
}
public void getTickets() {
//this method users usersXML from above and needs to execute after receiving the results
}
If you have a class:
public class ViewTicket extends Activity {
public static <result> recieveResults(Context context, String result2) {
ViewTicket ticket = (ViewTicket) context;
return <result>
}
public void getTickets(<result> result) {
// user <result> as you wish.
SharedPreference pref = this.getSharedPreferences("MyPref", 0);
}
}
Call the static method and pass the object to it.
ViewTicket myTicket = new ViewTicket();
<result> = ViewTicket.recieveResults(myTicket, "<someString>");
myTicket.getTickets(<result>);

Categories