/***
	Copyright (c) 2008 CommonsWare, LLC
	
	Licensed under the Apache License, Version 2.0 (the "License"); you may
	not use this file except in compliance with the License. You may obtain
	a copy of the License at
		http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

package com.commonsware.android.files;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class ReadWriteFileDemo extends Activity {
	EditText editor;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		editor=(EditText)findViewById(R.id.editor);
		
		Button btn=(Button)findViewById(R.id.close);
		
		btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	public void onResume() {
		super.onResume();
		
		try {
			InputStream in=openFileInput("notes.txt");
			
			if (in!=null) {
				BufferedReader reader=new BufferedReader(new InputStreamReader(in));
				String str;
				StringBuffer buf=new StringBuffer();
				
				while ((str = reader.readLine()) != null) {
					buf.append(str+"\n");
				}
				
				in.close();
				editor.setText(buf.toString());
			}
		}
		catch (java.io.FileNotFoundException e) {
			// that's OK, we probably haven't created it yet
		}
		catch (Throwable t) {
			showAlert("Exception!", 0, t.toString(), "Cancel", true);
		}
	}
	
	public void onPause() {
		super.onPause();
		
		try {
			OutputStreamWriter out=new OutputStreamWriter(openFileOutput("notes.txt", 0));
			
			out.write(editor.getText().toString());
			out.close();		
		}
		catch (Throwable t) {
			showAlert("Exception!", 0, t.toString(), "Cancel", true);
		}
	}
}