Reputation: 185
I want to store a float variable as SharedPreferences in my fragment. So I try to set it up and edit it later, but I get an error in the line verbrauch = prefsver.getFloat("key", 0);
that the Integer cannot be cast to a Float variable, although I thought I‘m not even using an int there. Am I storing it a wrong way?
My code, it’s just a snipped so I hope I didn’t cut anything relevant:
public class ItemThreeFragment extends Fragment {
TextView textView11;
float verbrauch;
public static ItemThreeFragment newInstance() {
ItemThreeFragment fragment = new ItemThreeFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_item_three, container, false);
SharedPreferences prefsver = getActivity().getBaseContext().getSharedPreferences("myPrefsKeyv",
Context.MODE_PRIVATE);
verbrauch = prefsver.getFloat("key",0);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText et = (EditText) getActivity().findViewById(R.id.editText);
String str = et.getText().toString();
verbrauch = Float.valueOf(str);
SharedPreferences prefsver = getActivity().getSharedPreferences("myPrefsKeyv",
Context.MODE_PRIVATE);
prefsver.edit().putFloat("key", verbrauch)
.apply();
}
});
}
Upvotes: 1
Views: 1911
Reputation: 1344
0 is an int literal - not a float. Use 0f (with a suffix), or cast explicitly as (float)0.
Edit:
Also check whether you're actually storing a float, e.g. there could be some leftover value. The method will try to cast what is stored in prefs as float, and in case the cast doesn't succeed, it throws ClassCastException.
Upvotes: 2
Reputation: 521
verbrauch = prefsver.getFloat("key",0F);
would be correct. Note the F
after the 0
that makes it a float.
Upvotes: 1