sharedpreferences is not saving or loading my data Android - android

Here is my savaData and loadData method which is used to save and load data
public void saveData(){
SharedPreferences sharedPreferences= getActivity().getSharedPreferences("SubjectTitle", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
int i=0,n;
n=addArray.size();
for(Bunk b: addArray) {
editor.putString("Title"+i, b.getTitle());
editor.putInt("No_of_bunk"+i, b.getBunk_remain());
editor.putFloat("pre_of_att"+i, b.getPrecentageAtt());
i++;
}
editor.putInt("size_of_data",n);
editor.apply();
Toast.makeText(getActivity(),"data saved",Toast.LENGTH_SHORT).show();
}
public ArrayList<Bunk> loadData(){
SharedPreferences sharedPreferences= getActivity().getSharedPreferences("SubjectTitle", Context.MODE_PRIVATE);
int n=sharedPreferences.getInt("size_pf_data",Default);
String loadTitle;
int loadBunk;
float loadAtt;
for(int i=0;i<n;i++){
loadTitle=sharedPreferences.getString("Title"+i,DEFAULT);
loadBunk=sharedPreferences.getInt("No_of_bunk"+i,Default);
loadAtt=sharedPreferences.getFloat("pre_of_att"+i,def_ault);
addArray.add(new Bunk(loadTitle,loadBunk,loadAtt));
}
return addArray;
}
here is code which is used to load data from loadData method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup perent, Bundle savedInstanceState) {
super.onCreateView(inflater, perent, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_main, perent, false);
show=(ListView)v.findViewById(android.R.id.list);
addArray=loadData();
adapter=new BunkAdapter(addArray);
show.setAdapter(adapter);
return v;
}

First, use editor.commit(); to save data after puting them, or directly: editor.putString("Title"+i, b.getTitle()).commit();
Secondly, I believe you're thinking wrong, Shared Preferences is better for things like settings or small amounts of data, in your case, you should use SQLite to save large data.

Related

Infinite loop on settheme()

I am trying to change the app theme from the fragment using setTheme() method of an activity. But somehow its looping forever while trying to change. Here is my setTheme() method calls.
//XYZ Fragment class
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
if (mThemeName.equalsIgnoreCase("Mode 1")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getActivity().setTheme(R.style.Theme_One);
} else {
getActivity().setTheme(R.style.Theme_Two);
}
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//binding object of this fragment
binding = FragmentXYZBinding.inflate(inflater);
binding.switch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked){
setTheme("Mode 2");
}else {
setTheme("Mode 1");
}
});
return inflater.inflate(R.layout.fragment_setting, container, false);
}
public void setTheme(String name) {
SharedPreferences preferences = getActivity().getSharedPreferences("app", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ThemeName", name);
editor.apply();
// If i call this recreate() then it goes into infinite loop
// but without calling this I can't change theme on runtime
//getActivity().recreate();
}
Any idea about what could be wrong in here ?

How to clear shared preferences from fragment?

How i can clear shared preferences from fragment? Thank you
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent logout = new Intent(getActivity(), LoginActivity.class);
startActivity(logout);
Log.d(TAG, sharedPreferences.getString("username", ""));
Log.d(TAG, sharedPreferences.getString("password", ""));
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_logout, container, false);
}
That my fragment
you can directly use preference name and clear it from anywhere.
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("shared_pref_key").commit();
or
SharedPreferences preferences = context.getSharedPreferences("Mypref", Context.MODE_PRIVATE);
preferences .edit().clear().commit();
Use something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_logout, container, false);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login.conf", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent logout = new Intent(getActivity(), LoginActivity.class);
startActivity(logout);
Log.d(TAG, sharedPreferences.getString("username", ""));
Log.d(TAG, sharedPreferences.getString("password", ""));
// Inflate the layout for this fragment
return view;
}

Sharedpreferences fragment

I have created two fragments. The second fragment contains multiple edittexts.
The SharedPreference works well, but only on the last edittext. For the remaining, it doesn't save anything. At the last, when we write in the edittext, then saving and running again, the app still shows the previous saved date.
EditText et;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
et =(EditText) view.findViewById(R.id.strength_score);
et =(EditText) view.findViewById(R.id.strength_modif);
et =(EditText) view.findViewById(R.id.strength_tem_scor);
et =(EditText) view.findViewById(R.id.strength_tem_modi);
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", Context.MODE_PRIVATE);
et.setText(setting.getString("value", ""));
// Inflate the layout for this fragment
return view;
}
public void onStop( ){
super.onStop();
if(et.getText() != null) {
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", 0);
SharedPreferences.Editor editor = setting.edit();
editor.putString("value", et.getText().toString());
editor.commit();
}
}
}
Thanks for the help.
Do like this -
EditText et,et1,et2,et3;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
et =(EditText) view.findViewById(R.id.strength_score);
et1 =(EditText) view.findViewById(R.id.strength_modif);
et2 =(EditText) view.findViewById(R.id.strength_tem_scor);
et3 =(EditText) view.findViewById(R.id.strength_tem_modi);
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", Context.MODE_PRIVATE);
et.setText(setting.getString("value", ""));
et1.setText(setting.getString("value1", ""));
et2.setText(setting.getString("value2", ""));
et3.setText(setting.getString("value3", ""));
// Inflate the layout for this fragment
return view;
}
public void onStop( ){
super.onStop();
if(et.getText() != null) {
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", 0);
SharedPreferences.Editor editor = setting.edit();
editor.putString("value", et.getText().toString());
editor.putString("value1", et1.getText().toString());
editor.putString("value2", et2.getText().toString());
editor.putString("value3", et3.getText().toString());
editor.commit();
}
}
}

Showing error for MODE_PRIVATE within fragment in android

Showing error while using MODE_PRIVATE for sharedPreferences within onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.activity_package_categories, container, false);
SharedPreferences pref = getActivity().getSharedPreferences("PackageType", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("package_categories_id", position);
editor.commit();
return layout;
}
You should use it like this Context.MODE_PRIVATE.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.activity_package_categories, container, false);
SharedPreferences pref = getActivity().getSharedPreferences("PackageType", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("package_categories_id", position);
editor.commit();
return layout;
}
Add context in your code like :
SharedPreferences pref = getActivity().getSharedPreferences("PackageType", Context.MODE_PRIVATE);

How to call NumberPicker's onvaluechange from SharedPreferences?

I want to update the NumberPicker using the value stored in Shared Preferences. This is all happening inside a fragment, there is also a button which calls the onValueChange() method whenever the user clicks on it.
HomeFragment.java
import android.content.SharedPreferences;
import android.widget.NumberPicker;
public class HomeFragment extends Fragment {
NumberPicker numberPicker;
SharedPreferences sharedPref;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
numberPicker = (NumberPicker) rootView.findViewById(R.id.np);
//Populate NumberPicker values from minimum and maximum value range
//Set the minimum value of NumberPicker
numberPicker.setMinValue(0);
//Specify the maximum value/number of NumberPicker
numberPicker.setMaxValue(239);
//Gets whether the selector wheel wraps when reaching the min/max value.
numberPicker.setWrapSelectorWheel(true);
//Set a value change listener for NumberPicker
final NumberPicker.OnValueChangeListener np_listener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal){
//Statement goes here...
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("someInteger", newVal);
editor.commit();
}
};
numberPicker.setOnValueChangedListener(np_listener);
b1 = (Button) rootView.findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int oldValue = numberPicker.getValue();
numberPicker.setValue(oldValue + 1);
np_listener.onValueChange(numberPicker, oldValue, oldValue + 1);
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Whenever the NumberPicker value changes, I'm saving it in Preferences but where to retrieve the value? I know the code to retrieve:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int someInteger = sharedPref.getInt("someInteger", 0);
But where to put this code, inside onCreate() or onCreateView()? After the value is retrieved if it exists then how to call onValueChange() so that all the statements inside that method gets executed?
You don't have to call it from SharedPreferences.
Inside onCreateView, set the NumberPicker value using the setValue method.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ... some code ...
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// Use default value 0 if key does not exist
int someInteger = sharedPref.getInt("someInteger", 0);
numberPicker = (NumberPicker) rootView.findViewById(R.id.np);
numberPicker.setValue(someInteger);
// ...
}

Categories

Resources