之前讲过多线程了,现在讲数据库的储存。
手机的数据储存分为 : 手机本身+SD卡 + 云端,
现在先抛开云端吧,讲手机信息的储存。
所有例子:
例子一:用户登录信息的 获取(在后台获取)
打开后台
这是手机内部储存的,在data-data中
里面有很多apk,找到我们的是androidch11
这里有个xml文件,我们导出来
可以见到输入的信息:
有没有感觉有点意思?
虽然没有试过这样是否可以获取手机登录过的cookie,
但是想法还是有的
最后:退出app,自动销毁账号密码信息。
例子三:存数据,取数据(内部)
简单写一个信息:先存后取
例子四:内部数据的存储,还是在手机内部,data内
files文件夹下:
因为设定是追加信息,文件内容不会被覆盖!
只会追加。
例子五:SDCard卡的存储。(外部存储)
这个也是追加的数据,不是覆盖的!
移动文件前:
移动文件之后:这是复制
最后一个搜索的功能:搜索mp3文件,
先往sd卡添加三首音乐
点击搜索:
音乐可见。
公布所有代码:还有一个mystyle自定义按钮样式
一、MainActivity.java
package com.open_open.androidch11;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class MainActivity extends Activity {
private SharedPreferences sp; //共享的文件
private TextView showUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showUser=(TextView) findViewById(R.id.showUser);
}
//生命周期中的onstart,safeExit ,取出的文件在start才能存储,放在create中,又会被循环覆盖
protected void onStart() {
super.onStart();
//从Preferences中取出已登录用户信息
sp=PreferenceManager.getDefaultSharedPreferences(this);
//取值
String name=sp.getString("LoginName","未登录");
showUser.setText(name);
}
//登录页面跳转
public void toLogin(View view){
Intent intent=new Intent(this,LoginActivity.class);
startActivity(intent);
}
//安全退出
public void safeExit(View view){
if (sp!=null){
SharedPreferences.Editor editor=sp.edit();
editor.remove("LoginName");
editor.remove("LoginPwd");
editor.commit();
}
this.finish();
}
//Activity级别的Preferences
public void aptest(View view){
Intent intent = new Intent(this,TestOneActivity.class);
startActivity(intent);
}
//手机内置存储inner_save,文件输入流:FileOutputStream
public void inner_save(View view){
try{
//将会在安装目录下files文件夹中创建一个文件android2.txt
FileOutputStream out=openFileOutput("android2.txt",MODE_APPEND);
out.write("春眠不觉晓,处处闻啼鸟!".getBytes());
out.flush();
out.close();
Toast.makeText(this,"文件处理完毕!",3000).show();
}catch (Exception e){
e.printStackTrace();
}
}
//手机内置文件读取 inner_get,文件输入流:FileInputStream
public void inner_get(View view) {
try {
//从手机安装目录下files文件夹中读取到android2.txt
FileInputStream in= openFileInput("android2.txt");
byte[] bytes= new byte[in.available()];
in.read(bytes);
in.close();
Toast.makeText(this,new String(bytes),3000).show();
} catch (Exception e) {
e.printStackTrace();
}
}
//读写SdCard
public void sdcardTest(View view){
Intent intent=new Intent(this,SDCardActivity.class);
startActivity(intent);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<TextView
android:id="@+id/showUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="未登录"
android:textSize="18sp"
android:textColor="@android:color/holo_red_light"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
android:onClick="toLogin"
style="@style/mButton1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="安全退出"
android:onClick="safeExit"
style="@style/mButton1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Activity_Preferences"
android:onClick="aptest"
style="@style/mButton1"/>
<View
android:layout_width="match_parent"
android:layout_height="30sp"
android:background="@android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="内部文件_存储"
android:onClick="inner_save"
style="@style/mButton1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="内部文件_读取"
android:onClick="inner_get"
style="@style/mButton1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SDCard文件读写"
android:onClick="sdcardTest"
style="@style/mButton1"/>
</LinearLayout>
二、LoginActivity.java
package com.open_open.androidch11;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText uname,upwd;
private CheckBox isSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
uname=(EditText)findViewById(R.id.uname);
upwd=(EditText)findViewById(R.id.upwd);
isSave=(CheckBox)findViewById(R.id.isChecked);
}
public void doLogin(View view ){
String name=uname.getText().toString().trim();
String pwd=upwd.getText().toString().trim();
if (isSave.isChecked()) {
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(this);
//将用户名和密码储存起来【密码谨慎处理】
SharedPreferences.Editor editor=sp.edit();
editor.putString("LoginName",name);
editor.putString("LoginPwd",pwd);
editor.commit();
//向应用级别的Preferences中存储数据
Toast.makeText(this,"用户名"+name+"登录成功!",3000).show();
}
//关闭当前窗体,返回上一级
this.finish();
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="用户登录"
android:gravity="center"
android:textColor="@android:color/holo_blue_light"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="用户名:"
android:textSize="28sp"
android:textColor="@color/Mhuise"/>
<EditText
android:id="@+id/uname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入"
android:textSize="28sp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="密 码 : "
android:textSize="28sp"
android:textColor="@color/Mhuise"/>
<EditText
android:id="@+id/upwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入"
android:password="true"
android:textSize="28sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="记住密码" />
<CheckBox
android:id="@+id/isChecked"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
android:onClick="doLogin"
android:textSize="30sp"
android:gravity="center"
android:layout_marginTop="10sp"
android:textColor="@color/Mhuise"/>
</LinearLayout>
三、TestOneActivity.java (存储数据,取出数据)
package com.open_open.androidch11;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class TestOneActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_one);
}
//存数据 doSave
public void doSave(View view){
SharedPreferences sp=getPreferences(MODE_APPEND);
SharedPreferences.Editor edit=sp.edit();
edit.putString("sayHello","大家好!");
edit.commit();
}
//取数据 doGet
public void doGet(View view){
SharedPreferences sp=getPreferences(MODE_APPEND);
String str=sp.getString("sayHello","");
Toast.makeText(this,str,3000).show();
}
}
activity_test_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存数据"
android:onClick="doSave"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取数据"
android:onClick="doGet"
/>
</LinearLayout>
四、SDCardActivity.java
package com.open_open.androidch11;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SDCardActivity extends Activity {
private ListView list;
private ArrayAdapter adapter;
private List mp3list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sdcard);
list=(ListView)findViewById(R.id.musics);
mp3list=new ArrayList();
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,mp3list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(Intent.ACTION_VIEW);
Uri uri=Uri.parse("file:///sdcard/Music/"+mp3list.get(position));
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
}
});
}
//向SDCard写文件
public void doSave(View view){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//获取文件保存路径
String basePath=Environment.getExternalStorageDirectory().getAbsolutePath();
basePath=basePath+"/myfile/android2.txt";
File file=new File(basePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
//构建一个输出流
try {
FileOutputStream out=new FileOutputStream(file,true);
out.write("大家好才是真好".getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, basePath, 5000).show();
}else if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)){
Toast.makeText(this, "SDCard已经移除", 3000).show();
}else{
Toast.makeText(this, "没有找到SD卡!", 3000).show();
}
}
//读取sdcard内容
public void doRead(View view){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String basePath=Environment.getExternalStorageDirectory().getAbsolutePath();
basePath=basePath+"/myfile/android2.txt";
File file=new File(basePath);
if(file.exists()){
FileInputStream in;
try {
in = new FileInputStream(file);
byte[] bytes=new byte[in.available()];
in.read(bytes);
in.close();
Toast.makeText(this, new String(bytes), 5000).show();
} catch (Exception e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "没有找到文件", 3000).show();
}
}else{
Toast.makeText(this, "没有发现SD卡", 3000).show();
}
}
//移动文件
public void doMove(View view){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String basePath=Environment.getExternalStorageDirectory().getAbsolutePath();
String savePath=basePath+"/myfile/android2.txt";
String movePath=basePath+"/android2.txt";
File file=new File(savePath);
if(file.exists()){
FileInputStream in;
FileOutputStream out;
try {
in = new FileInputStream(file);
out=new FileOutputStream
(movePath);
byte[] bytes=new byte[1024];
int i=0;
while((i=in.read(bytes))!=-1){
out.write(bytes);
}
out.flush();
out.close();
in.close();
Toast.makeText(this, "文件移动完毕 ", 5000).show();
} catch (Exception e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "没有找到文件",
3000).show();
}
}else{
Toast.makeText(this, "没有发现SD卡", 3000).show();
}
}
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==1)
adapter.notifyDataSetChanged();
};
};
//搜索音乐
public void searchMusic(View view){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
final File file=new File(path);
if(file.exists()){
//开启一个线程取查找MP3文件
new Thread(new Runnable() {
@Override
public void run() {
File[] files=file.listFiles();//取出指定目下所有文件
for (File f : files) {
if(f.isFile() && f.getName().toUpperCase().endsWith(".MP3")){
//发出消息
mp3list.add(f.getName());
handler.sendEmptyMessage(1);
}
}
}
}).start();
}else{
Toast.makeText(this, "路径不存在",3000).show();
}
}else{
Toast.makeText(this, "找不到SD卡", 3000).show();
}
}
}
activity_sdcard.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="向SDCard写文件"
android:onClick="doSave"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取SDCard文件"
android:onClick="doRead"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="移动文件"
android:onClick="doMove"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索音乐"
android:onClick="searchMusic"
/>
<ListView
android:id="@+id/musics"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:listSelector="@android:color/holo_orange_light"
/>
</LinearLayout>
五、其他:
mystyle.xml 自定义样式
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="mButton1" parent="android:Widget.Button">
<item name="android:textSize">28sp</item>
<item name="android:gravity">center</item>
<item name="android:textColor">@color/colorPrimaryDark</item>
</style>
</resources>
color :
<color name="Mhuise">#666666</color>
权限开启:AndroidManifest.xml
<!-- 开启sdcard卡读 | 取 数据的权限! -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
好了,大家练习一下吧。