代码笔记Android开发Android 开发技术分享

安卓 数据保存方式

2017-11-09  本文已影响150人  _VITA

从方式来说,有四种;
从保存地方来说,有三种。
方式分类法:

在AndroidManifest.xml中加入访问SDCard的权限如下:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
补充:Android6.0之后,会弹窗出来,需要用户授权
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

保存地方分类法:

用法:

public static AAA queryAAACacheByKey(String key) {
        try {
            return db().find(Selector.from(AAA.class).where("tb_aaa_key", "=", key));
        } catch (DbException e) {
            UploadException.uploadInfo("queryAAACacheByKey : " + e.getMessage() + "\n key = " + key);
        }

        return null;
    }

public Selector where(String columnName, String op, Object value) {//根据key(表名)找到selector
        this.whereBuilder = WhereBuilder.b(columnName, op, value);
        return this;
    }
public <T> T find(Selector selector) throws DbException {
        if (!tableIsExist(selector.getEntityType())) return null;

        String sql = selector.limit(1).toString();
        long seq = CursorUtils.FindCacheSequence.getSeq();
        findTempCache.setSeq(seq);
        Object obj = findTempCache.get(sql);
        if (obj != null) {
            return (T) obj;
        }
      //以上就是根据selector获取字符串sql,先到cache去找有没有,没有则接下来去数据库查找内容

        Cursor cursor = execQuery(sql);
        if (cursor != null) {
            try {
                if (cursor.moveToNext()) {
                    T entity = (T) CursorUtils.getEntity(this, cursor, selector.getEntityType(), seq);
                    findTempCache.put(sql, entity);//存入cache
                    return entity;
                }
            } catch (Throwable e) {
                throw new DbException(e);
            } finally {
                closeQuietly(cursor);
            }
        }
        return null;
    }

Cursor对象可以理解为游标对象,凡是对数据有所了解的人,相信对此对象都不会陌生,在这里机不再累述。只提醒一点,在第一次读取Cursor对象中的数据时,一定要先移动游标,否则此游标的位置在第一条记录之前,会引发异常。

public Cursor execQuery(String sql) throws DbException {
        debugSql(sql);
        try {
            return database.rawQuery(sql, null);// 根据给定SQL,执行查询。
        } catch (Throwable e) {
            throw new DbException(e);
        }
    }
public void save(Object entity) throws DbException {
        try {
            beginTransaction();

            createTableIfNotExist(entity.getClass());
            execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity));

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }
public void delete(Object entity) throws DbException {
        if (!tableIsExist(entity.getClass())) return;
        try {
            beginTransaction();

            execNonQuery(SqlInfoBuilder.buildDeleteSqlInfo(this, entity));

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }
public void update(Object entity, String... updateColumnNames) throws DbException {
        if (!tableIsExist(entity.getClass())) return;
        try {
            beginTransaction();

            execNonQuery(SqlInfoBuilder.buildUpdateSqlInfo(this, entity, updateColumnNames));

            setTransactionSuccessful();
        } finally {
            endTransaction();
        }
    }
Context ctx = MainActivity.this;       
         SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        Editor editor = sp.edit();
        editor.putString("STRING_KEY", "string");
        editor.putInt("INT_KEY", 0);
        editor.putBoolean("BOOLEAN_KEY", true);
        editor.commit();
        //取出数据
        editor.getBoolean(key, false);
        editor.getInt(key, 0);

        //删
        editor.remove(key);
        editor.commit();
        //全删
        editor.clear().commit();
  1. 存 (图片举例)
        File imagefile;
        for (int i = 0; i < num; i++) {
            imagefile = new File(App.getInst().getCacheDir() +路径名, img.get(i).id + ".png");
            if (!imagefile.exists()) {//如果图片不存在,则下载
                DownloadImageUtils.getInstance().downLoadImage(img.get(i).image,img.get(i).id + ".png");
            }
        }
  

  public void downLoadImage(String url, final String name) {
        ImageRequest imageRequest = new ImageRequest(url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        if (response != null) {
                            saveBitmap(response, name);
                        } else {
                        }
                    }
                }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        mQueue.add(imageRequest);
    }

    private void saveBitmap(final Bitmap bitmap, final String name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(App.getInst().getCacheDir() +路径名);
                if (!file.exists()) {
                    file.mkdir();//Creates the directory named by this abstract pathname:app.getInst().getCacheDir()
                }

                File f = new File(App.getInst().getCacheDir() + 路径名), name);
                if (!f.exists()) {
                    try {
                        FileOutputStream out = new FileOutputStream(f);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);//压缩bitmap,否则很大
                        out.flush();
                        out.close();
                    } catch (FileNotFoundException e) {

                    } catch (IOException e) {
                    }
                } else {
                }
            }
        }).start();
    }

我们可以理解File是一个路由,可以根据路径找到我们想要的文件(们);

        Bitmap bitmap = null;
        try {
            FileInputStream fis = new FileInputStream(getApplicationContext().getCacheDir() + name);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (Exception e) {

        } catch (OutOfMemoryError e){

        }
public class MyProvider extends ContentProvider{
     @Override
     public int delete(Uri uri, String selection, String[] selectionArgs) {
         // TODO Auto-generated method stub
         return 0;
     }
 
     @Override
     public String getType(Uri uri) {
         // TODO Auto-generated method stub
         return null;
     }
 
     @Override
     public Uri insert(Uri uri, ContentValues values) {
         return null;
     }
 
     //在Create中初始化一个数据库
     @Override
     public boolean onCreate() {
         SQLiteDatabase db = this.getContext().openOrCreateDatabase("test_db.db3", Context.MODE_PRIVATE, null);
         db.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)");
         ContentValues values = new ContentValues();
         values.put("name", "test");
         db.insert("tab", "_id", values);
         db.close();
         return true;
     }
 
   //实现query方法
     @Override
     public Cursor query(Uri uri, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) {
         SQLiteDatabase db = this.getContext().openOrCreateDatabase("test_db.db3", Context.MODE_PRIVATE, null);
         Cursor c = db.query("tab", null, null, null, null, null,null);
         return c;
     }
 
     @Override
     public int update(Uri uri, ContentValues values, String selection,
             String[] selectionArgs) {
         // TODO Auto-generated method stub
         return 0;
     }
 }
  1. 在当前应用程序中定义一个ContentProvider。
<provider android:name=".MyProvider" android:authorities="com.test.MyProvider"/>
  1. 在当前应用程序的AndroidManifest.xml中注册此ContentProvider
  public class MainActivity extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          
         //获取上下文
         Context ctx = MainActivity.this;
         //获取ContentResolver对象
         ContentResolver resolver = ctx.getContentResolver();
         //获取Uri对象
         Uri uri = Uri.parse("content://com.test.MyProvider");
         //获取数据
         Cursor c = resolver.query(uri, null, null, null, null);
         c.moveToFirst();
         for(int i=0; i<c.getCount(); i++){
             int index = c.getColumnIndexOrThrow("name");
             String src = c.getString(index);
             Log.d("", src);
             c.moveToNext();
         }
     }
 }
  1. 其他应用程序通过ContentResolver和Uri来获取此ContentProvider的数据。
上一篇下一篇

猜你喜欢

热点阅读