SharedPreferences存儲+SD卡存儲
SharedPreferences
特點:
保存少量的數據,且這些數據的格式非常簡單。 存儲5種原始數據類型: boolean, float, int, long, String
比如應用程序的各種配置信息(如是否打開音效、是否使用震動效果、小遊戲的玩家積分等),記住密碼功能,音樂播放器播放模式。
使用方式
**步驟1:**得到SharedPreferences對象 getSharedPreferences(“文件的名稱”,“文件的類型”);
(1).Context.MODE_PRIVATE:指定該SharedPreferences數據只能被應用程序讀寫
(2)MODE_APPEND:檢查文件是否存在,存在就往文件追加內容,否則就創建新文件。
以下不在建議使用
(3).Context.MODE_WORLD_READABLE:指定該SharedPreferences數據能被其他
應用程序讀,但不能寫。
(4).Context,MODE_WORLD_WRITEABLE:指定該SharedPreferences數據能被其他應用程序寫,但不能讀。
**步驟2:**得到 SharedPreferences.Editor編輯對象
SharedPreferences.Editor editor=sp.edit();
**步驟3:**添加數據
editor.putBoolean(key,value)
editor.putString()
editor.putInt()
editor.putFloat()
editor.putLong()
**步驟4:**提交數據 editor.commit()或者apply()(推薦用這個.異步提交)
Editor其他方法: editor.clear() 清除數據 editor.remove(key) 移除指定key對應的數據
寫數據
//SP寫數據
private void write() {
//TODO 1:得到SharedPreferences對象
//參數一 xml文件的名字 參數二 模式 MODE_PRIVATE 指定該SharedPreferences數據只能被本應用程序讀寫
SharedPreferences preferences = getSharedPreferences("songdingxing", MODE_PRIVATE);
//TODO 2:獲得編輯對象
SharedPreferences.Editor editor = preferences.edit();
//TODO 3:寫數據
editor.putString("username","送定型");
editor.putInt("age",18);
editor.putBoolean("isMan",false);
editor.putFloat("price",12.4f);
editor.putLong("id",5425054250l);
//TODO 4:提交數據
editor.commit();
}
讀數據
//讀數據
private void read() {
//TODO 1:得到SharedPreferences對象
//參數一 xml文件的名字 參數二 模式 MODE_PRIVATE 指定該SharedPreferences數據只能被本應用程序讀寫
SharedPreferences preferences = getSharedPreferences("sgf", MODE_PRIVATE);
//TODO 2:直接讀取
//參數一 鍵 參數二 找不到的時候給默認值
String username=preferences.getString("username","");
int age=preferences.getInt("age",0);
boolean isMan=preferences.getBoolean("isMan",false);
float price=preferences.getFloat("price",0.0f);
long id=preferences.getLong("id",0l);
Toast.makeText(this, username+":"+age+":"+isMan+":"+price+":"+id, 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=".LoginActivity"
android:orientation="vertical"
android:gravity="center">
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_alignParentLeft="true"
android:id="@+id/cb_remember"
android:text="記住密碼"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_alignParentRight="true"
android:id="@+id/login"
android:text="登錄"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
java代碼
package com.example.day008;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private EditText username;
private EditText password;
private CheckBox cb;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
cb=(CheckBox)findViewById(R.id.cb_remember);
login=(Button)findViewById(R.id.login);
//TODO 讀取
sharedPreferences=getSharedPreferences("1705A",MODE_PRIVATE);
boolean ischeck= sharedPreferences.getBoolean("ischeck",false);
if(ischeck){
//讀到用戶名和密碼展現在頁面中,複選框被勾選
String username1=sharedPreferences.getString("username","");
String password1=sharedPreferences.getString("password","");
username.setText(username1);
password.setText(password1);
cb.setChecked(true);
}
//TODO 寫數據
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username2=username.getText().toString().trim();
String password2=password.getText().toString().trim();
//用戶名和密碼是否正確
if("sgf".equals(username2)&&"123456".equals(password2)){
//判斷記住密碼是否被選中
if(cb.isChecked()){//存
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("ischeck",true);
edit.putString("username",username2);
edit.putString("password",password2);
edit.commit();
}else{//清空
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("ischeck",false);
edit.commit();
}
}
}
});
}
}
輪播圖廣告
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sevenday.Fragments.FourFragment;
import com.example.sevenday.Fragments.oneFragment;
import com.example.sevenday.Fragments.threeFragment;
import com.example.sevenday.Fragments.twoFragment;
import com.example.sevenday.activities.Main2Activity;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private SharedPreferences preferences;
private ViewPager vpid;
private RadioGroup radiogroup;
private RadioButton b1;
private RadioButton b2;
private RadioButton b3;
private RadioButton b4;
private Button start;
private TextView djsId;
private List<Fragment> list=new ArrayList<>();
private int item=0;//默認顯示頁面
private int time=5;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==102){
djsId.setText("倒計時"+(--time)+"秒");
if (time==0){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}else if (msg.what==101){
vpid.setCurrentItem(++item);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("welcome", MODE_PRIVATE);
boolean flag = preferences.getBoolean("isdone", false);
if (flag){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
vpid = (ViewPager) findViewById(R.id.vpid);
radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
b1 = (RadioButton) findViewById(R.id.b1);
b2 = (RadioButton) findViewById(R.id.b2);
b3 = (RadioButton) findViewById(R.id.b3);
b4 = (RadioButton) findViewById(R.id.b4);
start = (Button) findViewById(R.id.start);
djsId = (TextView) findViewById(R.id.djs_id);
list.add(new oneFragment());
list.add(new twoFragment());
list.add(new threeFragment());
list.add(new FourFragment());
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (item!=list.size()-1){
handler.sendEmptyMessage(101);
}else {
timer.cancel();
}
}
},0,1000);
vpid.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
}) ;
//滑動事件
vpid.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
if (i==0){
b1.setChecked(true);
}else if (i==1){
b2.setChecked(true);
}else if (i==2){
b3.setChecked(true);
}else if (i==3){
b4.setChecked(true);
}
if (i==list.size()-1){
start.setVisibility(View.VISIBLE);
djsId.setVisibility(View.VISIBLE);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (time>0){
handler.sendEmptyMessage(102);
}else {
timer.cancel();
}
}
},0,1000);
}else {
start.setVisibility(View.GONE);
djsId.setVisibility(View.GONE);
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
//點擊事件
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId==R.id.b1){
vpid.setCurrentItem(0);
}else if (checkedId==R.id.b2){
vpid.setCurrentItem(1);
}else if (checkedId==R.id.b3){
vpid.setCurrentItem(2);
}else if (checkedId==R.id.b4){
vpid.setCurrentItem(3);
}
}
});
}
//開始點擊事件
public void startclick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}
文件存儲:
內部文件存儲openFileOutput
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput("aa.json", MODE_PRIVATE);
fileOutputStream.write("hello".getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
openFileInput
FileInputStream fileInputStream = null;
try {
fileInputStream= openFileInput("aa.json");
byte[] b = new byte[1024];
int len = 0;
while((len = fileInputStream.read(b)) != -1){
Log.i(TAG, "onClick: "+new String(b,0,len));
}
} catch (Exception e) {
e.printStackTrace();
}
外部文件存儲(SD卡)
必須要添加讀寫SD卡的權限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
package com.example.day008;
import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button login;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String externalStorageState = Environment.getExternalStorageState();
Log.i(TAG, "onCreate: "+externalStorageState);
File externalStorageDirectory = Environment.getExternalStorageDirectory();
Log.i(TAG, "onCreate: "+externalStorageDirectory.toString());
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Log.i(TAG, "onCreate: "+externalStoragePublicDirectory);
login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: ");
//運行時權限
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//獲取SD卡根路徑:
File file = Environment.getExternalStorageDirectory();
FileOutputStream out = null;
try {
//創建輸出流
out = new FileOutputStream(new File(file, "json.txt"));
out.write("呵呵呵俺哥哥".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.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){
if(grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "不行啊", Toast.LENGTH_SHORT).show();
}
}
}
}
改進後的代碼
把文件操作寫到同意授權的回調方法裏.
@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){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file = Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(file,"aa.json"));
fileOutputStream.write("aaa".getBytes());
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
Toast.makeText(this, "沒有權限", Toast.LENGTH_SHORT).show();
}
}
(1)添加讀寫SD卡的 權限
(2)FileUtils.java:四個方法:實現向SD卡中讀寫Bitmap圖片和json字符串
public class FileUtils {
//方法1:向SD卡中寫json串
public static void write_json(String json) {
//判斷是否掛載
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//獲取SD卡根路徑:mnt/shell/emulated/0
File file=Environment.getExternalStorageDirectory();
FileOutputStream out=null;
try {
//創建輸出流
out= new FileOutputStream(new File(file,"json.txt"));
out.write(json.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//方法2:從SD卡中讀取json串
public static String read_json() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = Environment.getExternalStorageDirectory();
FileInputStream inputStream = null;
StringBuffer sb=new StringBuffer();
try {
inputStream=new FileInputStream(new File(file,"json.txt"));
byte[] b=new byte[1024];
int len=0;
while((len=inputStream.read(b))!=-1){
sb.append(new String(b,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}else{
return "";
}
}
//方法3:從SD卡中讀取一張圖片
public static Bitmap read_bitmap(String filename) {//filename圖片名字
Bitmap bitmap=null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=Environment.getExternalStorageDirectory();
File file1 = new File(file, filename);
//BitmapFactory可以直接根據SD卡圖片路徑轉成一個bitmap對象
bitmap= BitmapFactory.decodeFile(file1.getAbsolutePath());
}
return bitmap;
}
//方法4:網絡下載一張圖片存儲到SD卡中
public static void write_bitmap(String url) {//網址
new MyTask().execute(url);
}
static class MyTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
FileOutputStream out=null;
InputStream inputStream=null;//網絡連接的輸入流
HttpURLConnection connection=null;//向SD卡寫的輸出流
try {
URL url= new URL(strings[0]);
connection= (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5*1000);
connection.setReadTimeout(5*1000);
if (connection.getResponseCode()==200){
inputStream = connection.getInputStream();
//TODO 獲取SD卡的路徑
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否掛載
File file = Environment.getExternalStorageDirectory();
out = new FileOutputStream(new File(file,"xiaoyueyue.jpg"));
byte[] bytes=new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
out.write(bytes,0,len);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//關流
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
return null;
}
}
}
案例備註:
private void checkAccess(String access,int code){
//Manifest.permission.READ_EXTERNAL_STORAGE
//檢查當前權限(若沒有該權限,值爲-1;若有該權限,值爲0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasAccess = ContextCompat.checkSelfPermission(getApplication(), access);
Log.e("PERMISION_CODE", hasAccess + "***");
if (hasAccess == PackageManager.PERMISSION_GRANTED) {
// TODO: 2019/6/15 獲得授權執行操作
if (code == 1) {
write_json("json");
}else if(code == 2){
read_json();
}
} else {
//若沒有授權,會彈出一個對話框(這個對話框是系統的,開發者不能自己定製),用戶選擇是否授權應用使用系統權限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, code);
// 第1個參數,當前上下文環境;
// 第2個參數,需要授權的字符串數組;
// 第3個參數,請求碼requestCode,在回調方法中會用到。
}
}else{
// TODO: 2019/6/15 非6.0直接使用
if (code == 1) {
write_json("json");
}else if(code == 2){
read_json();
}
}
}
//用戶選擇是否同意授權後,會回調這個方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// 第1個參數,請求碼,對應上述方法的第3個參數;
// 第2個參數,請求權限數組;
// 第3個參數,請求權限的結果數組。
if(requestCode==1) {
if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// TODO: 2019/6/15 獲得授權執行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
write_json("json");
} else {
// TODO: 2019/6/15 未獲得授權執行的操作
finish();
}
}else if(requestCode == 2){
if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// TODO: 2019/6/15 獲得授權執行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
read_json();
} else {
// TODO: 2019/6/15 未獲得授權執行的操作
finish();
}
}
}