SharedPreferences存儲+SD卡存儲
SharedPreferences存儲
特點
1、保存少量的數據,且這些數據的格式非常簡單。 存儲5種原始數據類型: boolean, float, int, long, String
2、比如應用程序的各種配置信息(如是否打開音效、是否使用震動效果、小遊戲的玩家積分等),記住密碼功能,音樂播放器播放模式。
寫數據
//寫數據
//參數一 xml文件的名字 參數二 模式 MODE_PRIVATE 指定該SharedPreferences數據只能被本應用程序讀寫
SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
//獲取編輯對象
SharedPreferences.Editor edit = preferences.edit();
//寫入數據的內容
edit.putInt("age", 18);
edit.putString("name", "科比");
edit.putBoolean("isMan", true);
edit.putFloat("price", 17.1f);
edit.putLong("id", 1234567);
//提交數據
edit.commit();
在執行完上面這段代碼後系統會在data文件夾下自動生成文件
文件的內容也會自動創建
讀數據
步驟1:得到SharedPreferences對象 getSharedPreferences(“文件的名稱”,“文件的類型”);
步驟2:讀取數據 String msg = sp.getString(key,defValue);
//讀數據
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences login = getSharedPreferences("login", MODE_PRIVATE);
String username = login.getString("name", "科比");
Toast.makeText(MainActivity.this, ""+username, Toast.LENGTH_SHORT).show();
}
});
案例(記住用戶登錄信息)
效果展示:
xml佈局代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main2Activity">
<LinearLayout
android:padding="8dp"
android:layout_margin="5dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="用戶名:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_username"
android:background="@drawable/border"
android:paddingLeft="5dp"
android:hint="請輸入用戶名"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
<LinearLayout
android:padding="8dp"
android:layout_margin="5dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="密 碼:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_password"
android:background="@drawable/border"
android:paddingLeft="5dp"
android:hint="請輸入密碼"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/cb_rem"
android:layout_marginLeft="70dp"
android:text="記住用戶"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_login"
android:layout_marginLeft="40dp"
android:text="登錄"
android:layout_width="195dp"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
java代碼:
public class Main2Activity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private CheckBox cbRem;
private Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
initViews();
//用戶第二次登錄
SharedPreferences welcome = getSharedPreferences("welcome", MODE_PRIVATE);
//判斷是否記住
boolean isCk = welcome.getBoolean("isCk", false);
if (isCk){
String username = welcome.getString("username", "");
String password = welcome.getString("password", "");
etUsername.setText(username);
etPassword.setText(password);
cbRem.setChecked(true);
}
//登錄點擊事件
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//判斷多選框選中狀態
if (cbRem.isChecked()){
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
//存入sp
SharedPreferences welcome = getSharedPreferences("welcome", MODE_PRIVATE);
SharedPreferences.Editor edit = welcome.edit();
edit.putString("username",username);
edit.putString("password",password);
//中間值,複選框是否被選中
edit.putBoolean("isCk",true);
edit.commit();
}
}
});
}
private void initViews() {
etUsername = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
cbRem = (CheckBox) findViewById(R.id.cb_rem);
btnLogin = (Button) findViewById(R.id.btn_login);
}
}
外部文件存儲(SD卡)
重要代碼
(1)Environment.getExternalStorageState(); 判斷SD卡是否
(2)Environment.getExternalStorageDirectory(); 獲取SD卡的根目錄
(3)Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 獲取SD卡公開目錄pictures文件夾
讀寫權限
必須在清單文件中添加讀寫權限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
爲了更好的用戶體驗,6.0及之後的版本需要動態添加讀寫權限
//運行時權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//添加權限
String[] strings = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//參數一:添加的權限數組,參數二:請求碼
requestPermissions(strings, 100);
}
我們可以去查看用戶是否授權
//用戶是否授權
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "確定", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
}
}
接下來補全代碼,測試效果
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main3Activity">
<Button
android:id="@+id/btn_write"
android:text="Write"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_read"
android:text="Read"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
java:
public class Main3Activity extends AppCompatActivity {
private Button btnWrite;
private Button btnRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
btnRead = (Button) findViewById(R.id.btn_read);
btnWrite = (Button) findViewById(R.id.btn_write);
//運行時權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] strings = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(strings, 100);
}
//讀取SD卡數據
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//獲取SD卡的根路徑
File file = Environment.getExternalStorageDirectory();
FileInputStream fis = null;
StringBuffer stringBuffer = new StringBuffer();
try {
fis = new FileInputStream(new File(file,"a.txt"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fis.read(bytes))!=-1){
stringBuffer.append(new String(bytes,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//吐司從SD卡中讀取到的信息
Toast.makeText(Main3Activity.this, ""+stringBuffer, Toast.LENGTH_SHORT).show();
}
});
//寫入SD卡數據
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//獲取SD卡的根路徑
File file = Environment.getExternalStorageDirectory();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(file, "a.txt"));
fos.write("這是信息".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
//用戶是否授權
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "確定", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
}
}
}
案例(從網絡下載圖片保存到SD卡,再讀取到頁面)
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main4Activity">
<Button
android:id="@+id/btn_load"
android:text="下載圖片"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_set"
android:text="設置圖片"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv_pic"
android:src="@mipmap/ic_launcher_round"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
java:
public class Main4Activity extends AppCompatActivity {
private Button btnLoad;
private Button btnSet;
private ImageView ivPic;
private String picUrl = "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
btnLoad = (Button) findViewById(R.id.btn_load);
btnSet = (Button) findViewById(R.id.btn_set);
ivPic = (ImageView) findViewById(R.id.iv_pic);
//從網絡上下載圖片存儲到SD卡中
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//開啓網絡下載的異步任務
new MyTask().execute(picUrl);
}
});
//從文件中讀取圖片
btnSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = Environment.getExternalStorageDirectory();
Bitmap bitmap = BitmapFactory.decodeFile(new File(file, "a.jpg").getAbsolutePath());
ivPic.setImageBitmap(bitmap);
}
});
}
class MyTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
//寫數據的流
FileOutputStream fos = null;
//讀數據的流
InputStream is = null;
//向SD卡寫的輸入流
HttpURLConnection connection = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
//判斷響應碼是否爲200
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
//判斷SD卡是否掛載
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//獲取SD卡路徑
File file = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(file, "a.jpg"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//關閉流
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
return null;
}
}
}