【发布时间】:2019-05-16 17:45:10
【问题描述】:
我正在将 EditText 保存到 SharedPreferences,但我无法在 Fragment 中看到保存的文本。 有人可以告诉我我做错了什么,以及我在我的 apk 中使用 SharedPreferences 的方式。
这是我在 MainActivity 中保存数据的代码。
public static final String Save_Search = "Save_Search";
public EditText searchPlugin;
public String textForSearch;
searchPlugin = findViewById(R.id.etSearch);
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(Save_Search, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(editText, searchPlugin.getText().toString()); editor.putString(Save_Search, searchPlugin.getText().toString());
Log.d("Test", searchPlugin.getText().toString());
//This is saving me the typed text.
}
public void updateView() {
searchPlugin.setText(textForSearch);
}
这是EditText的布局
<EditText android:id="@+id/etSearch" android:imeOptions="actionGo|flagNoExtractUi" style="@style/SearchEditText.MainSearch" />
这是片段
public class FragmentHistory extends Fragment {
View paramView;
TextView textView;
public FragmentHistory() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.history_item, container, false);
textView = paramView.findViewById(R.id.tvHistoryName);
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String text = pref.getString("Save_Search", "");
textView.setText(text);
return paramView;
}
}
这是历史布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:background="@drawable/selector_btn_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@id/ivHistory" style="@style/ivHistory" />
<TextView android:id="@id/tvHistoryName" android:layout_height="38dp" style="@style/TextViewQuery"/>
<ImageView android:id="@id/imgViewSetQuery" style="@style/ImageViewSetQuery" />
<TextView android:textSize="@dimen/search_font" android:textColor="@android:color/white"
android:gravity="center" android:id="@id/btnDelete" android:background="@color/red" android:paddingLeft="5.0dip"
android:paddingRight="5.0dip" android:visibility="gone" android:longClickable="false"
android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="@string/Delete" />
</LinearLayout>
【问题讨论】:
-
在保存编辑文本的内容时调试程序时看到了什么?
-
你在想主要活动吗?
-
我在想,为什么你的应用程序崩溃了?因为空指针异常?编辑您的帖子并告诉我们确切的错误。
-
目前它没有告诉任何错误,并且在日志中显示编辑文本已保存,但在片段中未显示。我将编辑代码。
标签: android xml android-fragments sharedpreferences