安卓android sharepreference数据存储,保存输入框里面的数据
Fragment 里面 使用轻量级的数据存储sharepreference ,代码思路清晰。保存输入框里面的数据,实现按钮保存。
个人项目中简单清晰代码:
赵存档 编写 ,可以参考:
类继承Fragment实现点击事件:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.wifi,container, false); view.findViewById(R.id.openwifi).setOnClickListener(this); view.findViewById(R.id.closewifi).setOnClickListener(this); wifiurl = (EditText)view.findViewById(R.id.editText1); wificom = (EditText)view.findViewById(R.id.editText2); wificamera = (EditText)view.findViewById(R.id.editText3);
sharedPreferences = getActivity().getSharedPreferences("WifiSettings", Activity.MODE_PRIVATE); //私有数据; String str_wifiurl=sharedPreferences.getString("wifiurl", "192.168.8.1"); String str_wificom = sharedPreferences.getString("wificom", "2016"); String str_wificamera = sharedPreferences.getString("wificamera", "8083"); wifiurl.setText(str_wifiurl); wificom.setText(str_wificom); wificamera.setText(str_wificamera); return view; }
本代码来源个人博客:http://www.cnblogs.com/xiaobo-Linux/
保存数据:
public void savewifisettings(){ sharedPreferences = getActivity().getSharedPreferences("WifiSettings", Activity.MODE_PRIVATE); //私有数据; Editor editor = sharedPreferences.edit();//获取编辑器 editor.putString("wifiurl",wifiurl.getText().toString()); editor.putString("wificom",wificom.getText().toString()); editor.putString("wificamera",wificamera.getText().toString()); editor.commit();//提交修改 }
按钮保存:
@Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.openwifi: savewifisettings();//开启wifi的时候保存一下设置 } }
查看xml数据: