简体   繁体   中英

Getting a SharedPreference value in a non-activity class from a fragment

I'm trying to access SharedPreferences values in non-activity class. Preferences are defined and saved in fragment. There are three values I'm getting from seek bars, one for each of the red, green and blue color. Seek bar goes from 0 to 255 and SharedPreferences work, value is saved when I exit the app.

I'm trying to get the values in other class and then send them with POST request, but I'm sure how to get them. Can you help me?

Fragment:

public class SettingsFragment extends Fragment {

public static SharedPreferences preferences;
    public static SharedPreferences.Editor editor;

    public static final String RED_PROG = "RED_BAR";
    public static int redValue;

    public static final String GREEN_PROG = "GREEN_BAR";
    public static int greenValue;

    public static final String BLUE_PROG = "BLUE_BAR";
    public static int blueValue;

    public static final String DIMMER_PROG = "DIMMER_BAR";
    public static int dimmerValue;

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_settings, container, false);

        preferences = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

        getRedBar();
        getGreenBar();
        getBlueBar();

        return view;
    }

    public void onResume() {
        super.onResume();

        redBar.setProgress(preferences.getInt(RED_PROG,0));
        greenBar.setProgress(preferences.getInt(GREEN_PROG,0));
        blueBar.setProgress(preferences.getInt(BLUE_PROG,0));
        dimmerBar.setProgress(preferences.getInt(DIMMER_PROG,0));
    }

    public void onPause() {
        super.onPause();

        editor = preferences.edit();

        redValue = redBar.getProgress();
        greenValue = greenBar.getProgress();
        blueValue = blueBar.getProgress();
        dimmerValue = dimmerBar.getProgress();

        editor.putInt(RED_PROG, redValue);
        editor.putInt(GREEN_PROG, greenValue);
        editor.putInt(BLUE_PROG, blueValue);
        editor.putInt(DIMMER_PROG, dimmerValue);

        editor.commit();
    }
}

Other class (color values should be in RgbCapability insted of zeroes):

public class ContextCommunication {

    public static void sendPref(){

      RgbCapability rgbCapability = new RgbCapability(0,0,0);
      Light light = new Light(true,rgbCapability, 0);
      Post post = new Post("Zagreb", light);

      Call<Post> call = MainActivity.apiService.savePost(post);

      textViewResult.setText(post.toString());

      call.enqueue(new Callback<Post>() {
          @Override
          public void onResponse(Call<Post> call, Response<Post> response) {

              if (!response.isSuccessful()) {
                  textViewResult.setText(response.code());
                  return;
              }

              Post postResponse = response.body();

              String content = "";
              content += "Code: " + response.code() + "\n";
              content += "location: " + postResponse.getLocation() + "\n";
              content += "light: " + postResponse.getLight() + "\n";


              //textViewResult.setText(content);
          }

          @Override
          public void onFailure(Call<Post> call, Throwable t) {
              textViewResult.setText(t.getMessage());
          }
      });
  }
}

get instance from preferences

sharedPreferences = getActivity().getSharedPreferences(preferences, 
Activity.MODE_PRIVATE);

save to preferences

sharedPreferences.edit().putBoolean(key, value).apply();

get from preferences

sharedPreferences.getBoolean(key, defaultValue);

I'm trying to access SharedPreferences values in non-activity class

sharedPreferences = textViewResult.getContext().getSharedPreferences(preferences, 
Activity.MODE_PRIVATE);
int redValue=sharedPreferences.getInt(RED_PROG,0);
...

If Context in not available in sendPref method then pass it to access SharedPreferences instance.

Use apply() instead of commit() if Api level is > 8

You can pass getContext() as parameter from fragment to non-activity class. Using the context you can get the shared preferences.

public static void sendPref(Context context) {
    context.getSharedPreference..... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM