android实验3---界面信息保存入SD卡, sp写入
实现内容:
编写一个界面。有三行内容分别是学号,姓名,班级。要求有5个按钮分别是写sd,读sd,清空界面内容,写sp,读sp。
如图:

1,activity_main.xml页面布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="34dp"
        android:text="学号" />
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="34dp"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="38dp"
        android:text="姓名" />
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/editText1"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_toLeftOf="@+id/button3"
        android:text="写sp" />
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button4"
        android:layout_alignLeft="@+id/button2"
        android:text="读sp" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button4"
        android:layout_marginBottom="89dp"
        android:layout_toLeftOf="@+id/editText2"
        android:text="写入sd" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button4"
        android:layout_alignLeft="@+id/editText2"
        android:layout_marginBottom="17dp"
        android:text="清空" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button3"
        android:text="读出sd" />
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button4"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="44dp"
        android:text="班级" />
    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignRight="@+id/editText2"
        android:layout_toRightOf="@+id/button1"
        android:ems="10" />
</RelativeLayout>
  
具体布局内容如上,布局不太完美,基本实现界面内容。
2,MainActivity.java文件内容
package com.ligang;
//import com.dxxy.lab3.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//import com.dxxy.lab2.R;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
	private Button loginBt,loginBt1,Rdsp,RdBt,clear;
	private EditText qqNo,qqPsw,banji;
	SharedPreferences sp;//数据读写变量  
	Editor edit; //Editor编辑对象
	
	private File sdCardDir;//sd卡路径
	private File saveFile;//文件名
	private FileOutputStream outStream;//输入文件流
	private FileInputStream inStream;//输入文件
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		loginBt1 = (Button) findViewById(R.id.button1);
		RdBt = (Button) findViewById(R.id.button2);
		
		clear =(Button) findViewById(R.id.button3);
		
		loginBt = (Button)findViewById(R.id.button4);
		Rdsp = (Button)findViewById(R.id.button5);
		qqNo = (EditText)findViewById(R.id.editText1);
		qqPsw = (EditText)findViewById(R.id.editText2);
		banji = (EditText)findViewById(R.id.editText3);
		
		sp = this.getSharedPreferences("201521111012",MODE_WORLD_READABLE);  
		//利用edit()方法获取Editor对象。
		edit = sp.edit(); 
		
		//监听写sp button,完成xml文件写入功能
		loginBt.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				if(qqNo.getText().toString().equals("")||qqPsw.getText().toString().equals("")){
					Toast toast = Toast.makeText(getApplicationContext(), "请输入学号,姓名", Toast.LENGTH_SHORT);
					toast.show();
				}
				
				
				
				else{
					//通过Editor对象存储key-value键值对数据
										edit.putString("学号",qqNo.getText().toString()); 
										edit.putString("姓名",qqPsw.getText().toString()); 
										edit.putString("班级",banji.getText().toString());
										//通过commit()方法提交数据
										edit.commit();  
										Toast toast = Toast.makeText(getApplicationContext(),
												"sp写入成功", Toast.LENGTH_SHORT);
										toast.show();
				}
			}
		});
		
		//3 完成用户名密码的读取功能
		Rdsp.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				if(null!=sp.getString("学号",""))
				{
					qqNo.setText(sp.getString("学号",""));
				}
				if(null!=sp.getString("姓名",""))
				{
					qqPsw.setText(sp.getString("姓名",""));
				}
				if(null!=sp.getString("班级",""))
				{
					banji.setText(sp.getString("班级",""));
				}
				Toast toast = Toast.makeText(getApplicationContext(),
						"sp读入成功", Toast.LENGTH_SHORT);
				toast.show();
			}
		});
		
		//监听写文件button,完成文件写入功能
		loginBt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (qqNo.getText().toString().equals("")
						|| qqPsw.getText().toString().equals("")) {
					Toast toast = Toast.makeText(getApplicationContext(),
							"请输入学号姓名", Toast.LENGTH_SHORT);
					toast.show();
				} else {
					Toast toast = Toast.makeText(getApplicationContext(),
					"开始写入文件", Toast.LENGTH_SHORT);
					toast.show();
					Write_Files("201521111012.txt",qqNo.getText().toString());
					Write_Files("ligang.txt",qqPsw.getText().toString());
					Write_Files("dianxin.txt",banji.getText().toString());
					/*Toast toast = Toast.makeText(getApplicationContext(),
							"写入文件成功", Toast.LENGTH_SHORT);
					toast.show();*/
				}
			}
		});
		
		
		//5 完成用户名密码的读取功能
				RdBt.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if(null!=Read_Files("201521111012.txt"))
						{
							qqNo.setText(Read_Files("201521111012.txt"));
						}
						if(null!=Read_Files("ligang.txt"))
						{
							qqPsw.setText(Read_Files("ligang.txt"));
						}
						if(null!=Read_Files("dianxin.txt"))
						{
							banji.setText(Read_Files("dianxin.txt"));
						}
					}
				});
		
			//完成界面内容清空功能	
				clear.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						qqNo.setText("");
						qqPsw.setText("");
						banji.setText("");
						
						Toast toast = Toast.makeText(getApplicationContext(),
								"界面内容成功清除", Toast.LENGTH_SHORT);
						toast.show();
					}
				});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void Write_Files(String fileName, String strContent) {
		sdCardDir = Environment.getExternalStorageDirectory();
		saveFile = new File(sdCardDir, fileName);
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 创建 初始化 流对象
			try {
				outStream = new FileOutputStream(saveFile);
			} catch (FileNotFoundException e) {
				Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				// 把内容写入文件
				outStream.write(strContent.getBytes());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, "文件未发现异常!", Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, "文件读写异常!", Toast.LENGTH_SHORT).show();
			} catch (NullPointerException e) {
				Toast.makeText(this, "文件读写空指针异常!", Toast.LENGTH_SHORT).show();
			} finally {
				try {
					// 关闭文件输出流
					outStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Toast.makeText(this, "文件读写异常!", Toast.LENGTH_SHORT).show();
				}
				Toast.makeText(this, "文件写入成功!", Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(this, "内存卡不存在!", Toast.LENGTH_SHORT).show();
			return;
		}
	}
	// 3 完成文件读操作功能
	private String Read_Files(String fileName) {
		sdCardDir = Environment.getExternalStorageDirectory();
		saveFile = new File(sdCardDir, fileName);
		int len;
		// 然后创建一个字节数组输出流
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 创建 初始化 流对象
			try {
				inStream = new FileInputStream(saveFile);
				Log.v("Instance inStream", "实例化inStream!");
			} catch (FileNotFoundException e) {
				Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show();
				return null;
			}
			try {
				Log.v("Read", "读数据!");
				Toast.makeText(this, "文件读取成功!", Toast.LENGTH_SHORT).show();
				while ((len = inStream.read(buffer)) != -1) {
					ostream.write(buffer, 0, len);
				}
				Log.v("Read", "读成功!");
			} catch (IOException e) {
				Toast.makeText(this, "读 异常!", Toast.LENGTH_SHORT).show();
			}
			try {
				// 最后关闭输入流和输出流
				inStream.close();
				ostream.close();
				Log.v("Read", "读成功!");
			} catch (IOException e) {
				Toast.makeText(this, "读 异常!", Toast.LENGTH_SHORT).show();
			}
			String str = new String(ostream.toByteArray());
			Log.v("Disp", "文本显示!");
			return str;
		} else {
			Toast.makeText(this, "内存卡不存在!", Toast.LENGTH_SHORT).show();
			return null;
		}
	}
}
  
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号