gpt4 book ai didi

android - 在 fragment 中加载 preferenceactivity 值错误

转载 作者:行者123 更新时间:2023-11-29 14:38:58 25 4
gpt4 key购买 nike

嘿,我在以下代码中收到错误:getDefaultSharedPreferences。我该如何解决这个问题?我正在尝试从我的 PreferenceActivity 加载 prefUsername 的 edittext 值。我尝试使用 getSharedPreferences 但返回 null 因为 PreferenceActivity 将其数据存储在 DefaultSharedPreferences 中。提供任何帮助。

错误是:PreferenceManager 类型中的方法 getDefaultSharedPreferences(Context) 不适用于参数 (RunawayFragment)

全类:

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

最佳答案

您需要将上下文传递给 getDefaultSharedPreferences(),您可以通过调用 getActivity() 获取该上下文。

SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());

关于android - 在 fragment 中加载 preferenceactivity 值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com