Android NoSQL之SnappyDB
常规到的Android开发需要SQLite或者ORMLite这样的数据库存储数据,但是在有些情况下,基于键值对的数据存储效率更高,使用更便捷,在平台级的Java EE项目中,有一种去SQL的趋势和技术,Android平台上也有此类NoSQL技术解决方案,SnappyDB就是一款Android平台上的开源数据存储NoSQL解决方案。
SnappyDB在github上的项目地址:https://github.com/nhachicha/SnappyDB
一个简单的例子:
package app.zhangphil.app; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.snappydb.DB; import com.snappydb.DBFactory; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private String TAG = "数据库调试"; private String DB_NAME = "zhangphil_db"; private String CLASS = "class"; private int studentCount = 20; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); writeDB(); } @Override protected void onResume() { super.onResume(); readDB(); } private static class Student { public String name; public int id; public AClass aClass; } private static class AClass { public String name; public ArrayList<Student> students = new ArrayList<>(); } private void writeDB() { try { DB snappydb = DBFactory.open(getApplicationContext(), DB_NAME); AClass aClass = new AClass(); aClass.name = "一个班级"; for (int j = 0; j < studentCount; j++) { Student student = new Student(); student.name = "学生" + j; student.id = j; student.aClass = aClass; aClass.students.add(student); } snappydb.put(CLASS, aClass); snappydb.close(); } catch (Exception e) { e.printStackTrace(); } } private void readDB() { try { DB snappydb = DBFactory.open(getApplicationContext(), DB_NAME); AClass aClass = snappydb.getObject(CLASS, AClass.class); Log.d(TAG, aClass.students.size() + ""); snappydb.close(); } catch (Exception e) { e.printStackTrace(); } } }
注意存储的数据结构对象要static。
不要忘记加Android的存取权限。
代码运行的结果输出正确的值20.
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/3112.html