Reputation: 2621
hey im getting an error at: getDefaultSharedPreferences
in the following code. How can i solve this? i am trying to load the edittext value of prefUsername from my PreferenceActivity. I tried using getSharedPreferences
but that returns null as the PreferenceActivity stores its data in DefaultSharedPreferences
. Any help is appriciated.
The error is:
The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (RunawayFragment)
The whole class:
public class RunawayFragment extends DialogFragment {
public static RunawayFragment newInstance() {
RunawayFragment f = new RunawayFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getDialog() != null) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
View root = inflater.inflate(R.layout.runaway_fragment, container, false);
return root;
}
@SuppressLint("NewApi")
@Override
public void onStart() {
super.onStart();
// User Picture
final SharedPreferences sharedPreference = this.getActivity().getSharedPreferences("pref_key", Context.MODE_PRIVATE);
String picturePath = sharedPreference.getString("img_path", null);
ImageView imageView = (ImageView) getView().findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
//User Name
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(RunawayFragment.this);
String getUsernameText = sharedPreference.getString("prefUsername", null);
TextView setUsername = (TextView) getView().findViewById(R.id.username);
setUsername.setText(getUsernameText);
// change dialog width
if (getDialog() != null) {
int fullWidth = getDialog().getWindow().getAttributes().width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
fullWidth = size.x;
} else {
Display display = getActivity().getWindowManager().getDefaultDisplay();
fullWidth = display.getWidth();
}
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
.getDisplayMetrics());
int w = fullWidth - padding;
int h = getDialog().getWindow().getAttributes().height;
getDialog().getWindow().setLayout(w, h);
}
}
}
Upvotes: 1
Views: 1596
Reputation: 8021
You need to pass a context to getDefaultSharedPreferences()
, which you can get by calling getActivity()
.
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
Upvotes: 7