_036_Android_將資料儲存到 應用程式中(私有的)
阿新 • • 發佈:2018-11-12
儲存 資料 出現 異常 :
是因為 , 這裡的 路徑 以及 儲存的方式 都 有問題 , 目前是執行 在androd中, android底層 是linux核心, linux 檔案系統
是根目錄是 一個 /
寫 File file = new File(“info.txt”); ---將資料 儲存 到 linux 根目錄/ 下, 而這時 當前的應用程式 不可能取得這樣的許可權的.
每個應用程式 可以 將資料 儲存到 自己 獨有的一個 檔案 夾 下
public class MainActivity extends AppCompatActivity { private Button loginBtn; private EditText userNameET; private EditText passwordET; private CheckBox rememberCB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控制元件 loginBtn=findViewById(R.id.loginBtn); userNameET=findViewById(R.id.userNameET); passwordET=findViewById(R.id.passwordET); rememberCB=findViewById(R.id.rememberCB); File file = new File("/data/data/com.lfz.qqlogin/info.txt"); if(file.exists()&&file.length()>0){ BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String s = reader.readLine(); String[] split = s.split("#"); userNameET.setText(split[0]); passwordET.setText(split[1]); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } loginBtn.setOnClickListener(new MyOnClickListener()); } //登入的方法 public void login(){ String userName = userNameET.getText().toString().trim(); String password = passwordET.getText().toString().trim(); //判斷是否已經輸入了使用者名稱和密碼 if(TextUtils.isEmpty(userName)||TextUtils.isEmpty(password)){ Toast.makeText(this,"請輸入qq號碼和密碼",Toast.LENGTH_SHORT).show(); return; } //判斷是否已經勾選了checkbox,如果已經勾選了則儲存userName和password boolean checked = rememberCB.isChecked(); if(checked){ //儲存資料 OutputStream os = null; try { File file = new File("/data/data/com.lfz.qqlogin/info.txt"); os = new FileOutputStream(file); String value=userName+"#"+password; os.write(value.getBytes()); System.out.println("hello"); Toast.makeText(this,"勾選了,儲存成功!",Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } finally { if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }else{ Toast.makeText(this,"未勾選",Toast.LENGTH_SHORT).show(); } } private class MyOnClickListener implements View.OnClickListener{ @Override public void onClick(View v) { int id = v.getId(); if(id==R.id.loginBtn){ login(); } } } }
請 設計 一下 android中 圖片的快取策略, 儲存到 裝置 中 :
每個應用都有自己的 儲存資料的資料夾, 有 cache 和 files文建這裡 可以去儲存 應用執行 時 需要一些資料 .
舉例 , 一個新聞客戶端, 如果 現在網路不可以用, 那麼 就預設的情況下給使用者顯示快取 cache 資料夾下的資料 。
如果網路可以用,那麼就 提示 使用者 當前 網際網路上伺服器的最新的資料 有 多少條,
然後 讓使用者去選擇是否 更新 資料,如果不選擇更新, 那麼就 不更新,
如果選擇更新, 那麼就將 快取cache 資料夾的資料給覆蓋掉, 這樣就可以 設計一套比較合理的快取策略.