zoukankan      html  css  js  c++  java
  • Adding a File to a Content Provider

      Occasionally, you might need to store a file in a database. The usual approach is to save
    the file to disk and then update the record in the database that points to the
    corresponding file name. 
    Android takes this protocol and automates it by defining a specific procedure for saving
    and retrieving these files. Android uses a convention where a reference to the file name
    is saved in a record with a reserved column name of _data. 
    When a record is inserted into that table, Android returns the URI to the caller. Once you
    save the record using this mechanism, you also need to follow it up by saving the file in
    that location. To do this, Android allows ContentResolver to take the Uri of the database
    record and return a writable output stream. Behind the scenes, Android allocates an
    internal file and stores the reference to that file name in the _data field.
    If you were to extend the Notepad example to store an image for a given note, you could
    create an additional column called _data and run an insert first to get a URI back. The
    following code demonstrates this part of the protocol: 
    ContentValues values = new ContentValues();
    values.put("title", "New note");
    values.put("note","This is a new note");
     
    //Use a content resolver to insert the record
    ContentResolver contentResolver = activity.getContentResolver();
    Uri newUri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values);
    Once you have the URI of the record, the following code asks the ContentResolver to
    get a reference to the file output stream: 
    ….
    //Use the content resolver to get an output stream directly
    //ContentResolver hides the access to the _data field where 
    //it stores the real file reference.
    OutputStream outStream = activity.getContentResolver().openOutputStream(newUri);
    someSourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    outStream.close();
    The code then uses that output stream to write to.

  • 相关阅读:
    杭电oj2032、2040、2042、2054、2055
    杭电oj2022-2030
    杭电oj2012-2021
    杭电oj2000-2011
    值得思考的几句话,放在这看看
    CEO 是一家创业公司的天花板
    致敬骄傲的产品人
    【新业务搭建】竞争情报业务规划及体系构建的思考——By Team
    微软威胁情报中心总经理的十句话——From John Lambert——太精辟了.......
    【调研与分析】标杆学习、知识管理和竞争情报的关系——From Team
  • 原文地址:https://www.cnblogs.com/enricozhang/p/1750332.html
Copyright © 2011-2022 走看看