如何在本地存储或保存和检索多个远程图像

时间:2014-11-10 16:12:02

标签: android local-storage

我在Android中寻找一种解决方案,将远程图像(从webservices检索到的URL)存储到本地(SDcard或Sqlite数据库或缓存)中,这样图像也可以在离线模式下显示。 因为我想在通话期间每次显示一张图片。

有没有解决方案?

1 个答案:

答案 0 :(得分:-1)

请按照以下步骤操作(一次只能检索一次图像):

  1. 从网址中将图片检索为位图。
  2. 将位图转换为字节数组。
  3. 将字节数组存储到SQLite数据库表的blob字段中。
  4. 从SQLite数据库表中获取blob。
  5. 将blob转换为字节数组。
  6. 将字节数组转换为位图。
  7. 最后,将Bitmap设置为Activity的ImageMap上的图像。
  8. public class ImageStoreAndRetrievalActivity extends Activity {

    private ImageView imageView;
    private DatabaseHandler dbHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_store);
        imageView = (ImageView)findViewById(R.id.imageView1);
        dbHandler = new DatabaseHandler(getApplicationContext());       
        new MyThread("http://www.fnordware.com/superpng/pnggrad8rgb.png");
        imageView.setImageBitmap(dbHandler.getBitmap(1));  // here 1 is id for the image into tbl_blob table in SQLite DB.
    }
    
    public class MyThread implements Runnable {
        private String url;
        private Bitmap bitmap = null;
        private Thread th;
        public MyThread(String url) {
            this.url = url;
            th = new Thread(this);
            th.start();
            try {
                th.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public void run() {
            URL fileUrl = null;  
    
            try {  
                fileUrl = new URL(url);  
                HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();  
                conn.setConnectTimeout(0);  
                conn.setDoInput(true);  
                conn.connect();  
                InputStream is = conn.getInputStream();  
                bitmap = BitmapFactory.decodeStream(is);  
                is.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }   
            dbHandler.insertBitmap(bitmap);
            Log.i("URL", url);
        }
    
    }
    

    }

        public static final String DATABASE_NAME = "blobdb";
        public static final int DATABASE_VERSION = 1;
        public static final String CREATE_BLOB_TABLE = "CREATE TABLE IF NOT EXISTS tbl_blob " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, img BLOB NOT NULL, description TEXT NULL)";
    

    公共类DatabaseHandler扩展了SQLiteOpenHelper {     私有上下文上下文;

    public DatabaseHandler(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }
    
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        // create all tables in 'btlocdb'
        createTables(db);
    }
    
    /** create all tables in 'btlocdb'.
     * @param db
     */
    public void createTables(SQLiteDatabase db) {       
        db.execSQL(CREATE_BLOB_TABLE);
    }
    
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        //db.execSQL("DROP TABLE IF EXISTS " + Consts.Table.DATABASE_NAME);
    
        // Create tables again
        //onCreate(db);
    }
    
    public void insertBitmap(Bitmap bm) 
    {
    
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, out);
        byte[] buffer=out.toByteArray();
    
        SQLiteDatabase db = this.getWritableDatabase();
    
    
        // Starts the transaction.
        db.beginTransaction();
        ContentValues values;        
        try 
        {
            values = new ContentValues();
            values.put("img", buffer); 
            values.put("description", "This is a description"); 
            // Inserting Row
            long i = db.insert("tbl_blob", null, values);
            Log.i("Insert", i + "");
            // Insert or update data into database successfully.
            db.setTransactionSuccessful();                                    
        }       
        catch (SQLiteException e) 
        {
            e.printStackTrace();
        }                      
        finally
        {
            db.endTransaction(); // Ending the transaction.
            db.close(); // Closing database connection
        }
    }
    
    public Bitmap getBitmap(int id){
        Bitmap bm = null;
        SQLiteDatabase db = this.getWritableDatabase();
        // Starts the transaction.
        db.beginTransaction();
        try 
        {                       
            String selectQuery = "select * from tbl_blob where id = " + id;
            Cursor cursor = db.rawQuery(selectQuery, null);
            Log.i("Cursor", cursor.getCount() + "");        
            if(cursor.getCount() > 0)
            {
    
                if (cursor.moveToFirst()) {
                    do {                        
                        byte[] blob = cursor.getBlob(cursor.getColumnIndex("img"));
                        ByteArrayInputStream imageStream = new ByteArrayInputStream(blob);
                        bm = BitmapFactory.decodeStream(imageStream);
                    } while (cursor.moveToNext());
                }               
            }                   
            db.setTransactionSuccessful();  
        }       
        catch (SQLiteException e) 
        {
            e.printStackTrace();
        }                      
        finally
        {
            db.endTransaction(); // Ending the transaction.
            db.close(); // Closing database connection
        }
        return bm;      
    }
    

    }

    希望这会对你有所帮助! 如果您对此问题有任何疑问,请与我们联系。感谢..