table of Contents
Extension:
- final variable: when used, it is directly replaced with his value
- String variable: when used, it is used by the link object address
- When using a Java local internal class or internal class, if the local variable of the method is called by the class, the local variable must be modified with the final keyword,
otherwise a compilation error will occur "Cannot refer to a non-final variable * inside an inner class defined in a different method " - Relative path: ... / is to go up one level
Types of storage in Android: sharedPreferences, internal storage, external storage, Sqlite database
One. SharedPreferences storage
- sharedPreferences
1.1 获取sharedPreferences对象 * 函数getSharePreferences(String fileName,int mode) (fileName是最终要存的文件名;mode权限一般就是一个安卓常量) mode里面有内容参数: * MODE_PRIVATE:仅供自己的app使用 * MODE_MULTI_PROCESS:多个app可读,跨应用 * MODE_APPEND:追加内容,不存在则创建在写入 * 函数getPreferences(int mode) (不常用,只读文件。eg:sharedPreferences mysp=getshsharedPreferences()) 1.2 获取sharedPreferences子对象 SharePreferences.Editor editor=mysp.edit(); 1.3 向editor添加数据 editor.putString(key,value) editor.putInt(key,value) editor.putBoolean(key,value) 1.4 提交数据 editor.commit();
- Eg: Example (account, password save, click register to save)
final EditText username=(EditText) findViewById(R.id.username);//注意这里要在下面方法中使用,所以定义为final变量,具体原因,见上面的扩展*** final EditText password=(EditText) findViewById(R.id.password); Button regist=(Button) findViewById(R.id.regist); Button login=(Button) findViewById(R.id.login); //1.准备写入对象 final SharedPreferences mysp = getSharedPreferences("passport", MODE_PRIVATE); //在点击事件之前就已经连接到了SharedPreferences数据库,并设置了相应的文件名和使用权限模式 //2.写入 regist.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { //2.1获得数据 String input_username=username.getText().toString(); String input_password=password.getText().toString(); //2.2获得可编写对象 SharedPreferences.Editor editor=mysp.edit(); //这里获得了数据库的编写权限,就可以在下面编写了 //2.3放入数据 editor.putString("username", input_username); //这里通过编写权限声明的对象,在数据库中放入内容 editor.putString("password", input_password); //2.4提交 editor.commit(); //注意最后一定要提交 Toast.makeText(getApplicationContext(), "注册成功", 2).show(); } });
- Find where saved data
window-show view-other-android-file explorer-data-data-想要找的包的名称-shared prefs-存的文件-点击右上角红色按钮(pull a file from the device)-找到导出文件用记事本打开 上面例子中显示的数据如下: <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="username">zhangsan</string> //我输入的账号名 <string name="password">zhangsan</string> //我输入的密码 </map>
- Read sharedPreferences
mysp.getString(value,null) //第一个参数为:要从数据库中提取信息的名字,第二个参数是:如果没有信息要输出的备用值,可以设空 然后用if来验证,输入值和数据库中存在的值是否相匹配,如果匹配,就完成相应的操作,不匹配else,完成相应的操作 具体登录例子如下: //读取数据,点击登录验证 login.setOnClickListener(new OnClickListener() { //设置登录按钮点击事件 public void onClick(View arg0) { //获得填入的账号密码 String input_username=username.getText().toString(); String input_password=password.getText().toString(); //读取数据库的账号和密码 String exis_username=mysp.getString("username", null); //这里用到了getString(),与上面的putString)()相对于应 String exis_password=mysp.getString("password", null); //验证 if(input_username.equals(exis_username)&&input_password.equals(exis_password)){//if判断在这里 Intent intent=new Intent(MainActivity.this,Info.class);//这里设置了一个跳转界面 Toast.makeText(getApplicationContext(), "登录成功", 2).show(); } else{ Toast.makeText(getApplicationContext(), "账号或密码错误", 2).show(); } } });
- Registration settings, displayed if the account is the same, the account already exists
- Remember password
2. Internal storage I / O stream:
Features of internal storage I / O stream:
- Can only be accessed by the application that created it
- It ’s gone after uninstalling the app
- Avoid using it, GG is full when the memory is full
Output stream: openFileOutput (filename, mode) // Open the file output stream and specify the mode
Input stream: openFileInput (filename) // Open the file input stream and read
getDir (name, mode) // Get it in the app's data directory Create a subdirectory of name
getFileDir // Get the absolute path of the file
String [] Variable = fileList (); // Return all files under app's data
deleteFile (filename) // Delete files
记事本示例:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button savaButton=(Button)findViewById(R.id.save);
savaButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText text=(EditText)findViewById(R.id.text);//获取输入框的文本
String textString=text.getText().toString();
//创建一个 文件,用来写入
FileOutputStream file=null;//先准备一个输出文件的对象
try {
file=openFileOutput("first", MODE_PRIVATE);//对象=一个文件,打开文件
try {
file.write(textString.getBytes());//根据函数参数的类型,写入内容
file.flush();//清楚缓存
Toast.makeText(getApplicationContext(), "保存成功", 2).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//退出
Button quit=(Button)findViewById(R.id.quit);
quit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
//读取
Button read=(Button) findViewById(R.id.read);
read.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
FileInputStream readFile=openFileInput("first");//准备文件输入流对象
try {
byte [] buffer=new byte[readFile.available()];//实例化字节数组
readFile.read(buffer);//读取
readFile.close();//关闭
String data=new String(buffer);
EditText textEdit=(EditText)findViewById(R.id.text);
textEdit.setText(data);
System.out.println(data.toString());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//获取文件列表
String [] fileList=fileList();
for(int i=0;i<fileList.length;i++){
System.out.println(fileList[i]);
}
//获取绝对路径
System.out.println("绝对路径"+getFilesDir());
}
3. External storage
External storage does not only refer to the SD card, but generally refers to the external storage that can be recognized when connected to the computer.
After sava, the file exists in the data folder-media folder-0 folder-mytext (this is the document name and can be changed)
注意:在配置文件中需要限制读写权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
记事本示例:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------------------------------------------------------区别1----------------------------------------------------------------
//实例化外部文件对象
final File waitFile=new File(Environment.getExternalStorageDirectory(),"mytext");
Button savaButton=(Button)findViewById(R.id.save);
savaButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText text=(EditText)findViewById(R.id.text);//获取输入框的文本
String textString=text.getText().toString();
//创建一个 文件,用来写入
FileOutputStream file=null;//先准备一个输出文件的对象
try {
//-----------------------------------------------------------区别2-----------------------------------------------------
file=new FileOutputStream(waitFile);//对象=一个文件,打开文件
try {
file.write(textString.getBytes());//根据函数参数的类型,写入内容
file.flush();//清楚缓存
Toast.makeText(getApplicationContext(), "保存成功", 2).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//退出
Button quit=(Button)findViewById(R.id.quit);
quit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
//读取
Button read=(Button) findViewById(R.id.read);
read.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
//--------------------------------------------------------区别3---------------------------------------------------------
FileInputStream readFile=new FileInputStream(waitFile);//准备文件输入流对象
try {
byte [] buffer=new byte[readFile.available()];//实例化字节数组
readFile.read(buffer);//读取
readFile.close();//关闭
String data=new String(buffer);
EditText textEdit=(EditText)findViewById(R.id.text);
textEdit.setText(data);
System.out.println(data.toString());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//获取文件列表
String [] fileList=fileList();
for(int i=0;i<fileList.length;i++){
System.out.println(fileList[i]);
}
System.out.println("绝对路径"+getFilesDir());
}
}