我正在为我的项目使用可滚动标签 + 滑动导航。我使用 Shared Preferences 来存储表单的数据。我的 onClick 功能用于页面的保存按钮。
public void onClick(View v) {
SharedPreferences.Editor editor3 = settings3.edit();
editor3.putString("address", personal_info_address.getText().toString());
editor3.putString("age", personal_info_age.getText().toString());
editor3.putString("name", personal_info_name.getText().toString());
editor3.putString("diseases", personal_info_diseases.getText().toString());
editor3.commit();
}
重新打开应用程序后,我无法恢复数据。我可以使用相同的代码将表单详细信息保存在普通应用程序中,在使用可滚动选项卡 + 滑动导航时是否需要执行其他操作。
编辑:
我在片段类中实现了 clickListener,这是我的代码:
public class SettingsFragment extends Fragment {
public static EditText txtMessage;
public static EditText emergencyno;
Button button;
Context context;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.services, container, false);
emergencyno = (EditText) root.findViewById(R.id.settings_number);
txtMessage = (EditText) root.findViewById(R.id.settings_msg);
button = (Button) root.findViewById(R.id.save);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = txtMessage.getText().toString();
String no = emergencyno.getText().toString();
Log.d("HELLO : ", "data1");
SharedPreferences sharedpreferences = context
.getSharedPreferences("MyData", Context.MODE_PRIVATE);
Log.d("HELLO : ", "data2" + context);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("message", msg);
editor.putString("number", no);
editor.commit();
Log.d("HELLO : ", "data3" + msg + no);
String message = sharedpreferences.getString("message",
"defValue");
String phone_no = sharedpreferences.getString("number",
"defValue");
txtMessage.setText(message);
emergencyno.setText(phone_no);
Log.d("HELLO : ", "data4" + message + phone_no);
}
});
return root;
}
}
日志给出了我需要的正确值。但是在重新启动应用程序时,数据不会存储。我需要知道如何获取上下文。