android数据存储

 

app在运行过程中,需要保存用户的一些信息。例如登录状态、账户信息等,安卓提供了多种方式来保存用户的数据。

 

1.key-value 保存,通过SharedPreferences实现 

SharedPreferences sp = getSharedPreferences("test", Context.MODE_PRIVATE); 

sp.edit().putString("str", "hello").commit();

Log.e(TAG, "save1: "+sp.getString("str",null) );  

2.文件保存,把数据写入内部存储器中 

    File file = getFilesDir();

    Log.e(TAG, "save2: "+file.getAbsolutePath());

 

    File f2 = new File(file,"test.log");

    try {

      f2.createNewFile();

      //在文件中写入数据

      Log.e(TAG, "save2: "+f2.exists());

    } catch (IOException e) {

      e.printStackTrace();

    } 

3.数据库保存,通过SQLite 数据库读写结构化数据

通过openOrCreateDatabase创建数据库或者继承SQLiteOpenHelper实现

 

4.网络保存,通过http协议把数据保存在服务器上

 

  URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

 实例下载:https://files.cnblogs.com/files/bruce2020/TestSQLite.zip 

posted @ 2018-01-22 15:15  bruce_2020  阅读(214)  评论(0编辑  收藏  举报