退出软件时候保留的输入数据

在退出程序前保留所输入的数据

1.使用Context提供的OpenFileOutput()和OpenFileIntput();

OpenFileOutput(): 需要两个参数,第一个是key值,为了下次取出的时候使用;第二个是Context的方式,MODE_PRIVATE是默认的使用工作方式,会覆盖文件原有的内容,MODE_APPEND表示要往里面追加内容,可靠实际情况来定。
在xml视图加入EditeText用来输入,在activity里加入OpenFileOutput(),例:

 public void baocun(String inputText){
    	FileOutputStream out = null;
    	BufferedWriter writer = null;
    	try {
			out = openFileOutput("bt", Context.MODE_PRIVATE);
			writer = new BufferedWriter(new OutputStreamWriter(out));
			writer.write(inputText);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if (writer!=null) {
					writer.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		} 

可以在退出的时候使用此方法,即在onDestroy()调用

 protected void onDestroy() {
    	String inputText = edt1.getText().toString();
    	save(inputText);
    	super.onDestroy();
    }

OpenFileIntput(): 只需要一个参数,key值,即上次退出的时候OpenFileOutput()使用的那个,在activity里加入OpenFileIntput(),例:

public String  jiazai(){
    	FileInputStream in = null;
    	StringBuilder content = new StringBuilder();
    	BufferedReader reader = null;
    	
    	try {
			in = openFileInput("bt");
			reader = new BufferedReader(new InputStreamReader(in));
			String line = "";
			while ((line =reader.readLine())!=null) {
				content.append(line);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if (reader!=null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
    	
    	return content.toString();
    }

在程序开启的时候调用即onCreate()的调用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        edt1 = (EditText) findViewById(R.id.edt1);
        
        String inPut = load();
        if (!TextUtils.isEmpty(inPut)) {
			edt1.setText(inPut);
			edt1.setSelection(inPut.length());
		}
        
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值