如何存储图像从网址到SQLite的? [英] how to store image from url to sqlite?

查看:130
本文介绍了如何存储图像从网址到SQLite的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我在Adnroid内规划新的,我尝试组合JSONParse和SQLite,当我存储(插入)数据的SQLite我的专栏形象= NULL(SQLite中不保存)
如何从URL和存储(插入)获取图像的SQLite?

这是我的code主要活动

 公共类MainActivity延伸活动{    按钮Btngetdata;    // URL获得JSON数组
    私有静态字符串URL =htt​​p://10.0.2.2:81/bantulfolder/alldata.php;    私人字符串IMAGEURL =htt​​p://10.0.2.2:81/bantulfolder/;    私人字节[] logoImage;    // JSON节点名称
    私有静态最后弦乐TAG_DATA =数据;
    公共静态最后弦乐TAG_IDT =IDT;
    公共静态最后弦乐TAG_IDL =IDL;
    公共静态最后弦乐TAG_NAMA =非农产品市场准入;
    公共静态最后弦乐TAG_ALAMAT =alamat;
    公共静态最后弦乐TAG_IMAGE =形象;    JSONArray用户=无效;    私人数据库处理器databaseHelper;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        databaseHelper =新数据库处理器(MainActivity.this);        Btngetdata =(按钮)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(查看视图){
                新JSONParse()执行();
            }
        });
    }    私有类JSONParse扩展的AsyncTask<字符串,字符串,JSONObject的> {
        最后的字符串标记=AsyncTaskParseJson.java;
        私人ProgressDialog pDialog;        @覆盖
        在preExecute保护无效(){
            super.on preExecute();            pDialog =新ProgressDialog(MainActivity.this);
            pDialog.setMessage(获得的数据...);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        @覆盖
        受保护的JSONObject doInBackground(字符串参数... args){
            JSONParser jParser =新JSONParser();
            // URL从JSON入门
            JSONObject的JSON = jParser.getJSONFromUrl(URL);
            返回JSON;
        }        @覆盖
        保护无效onPostExecute(JSON的JSONObject){
            pDialog.dismiss();
            尝试{
                //获取JSON数组
                用户= json.getJSONArray(TAG_DATA);
                //通过所有用户环路
                的for(int i = 0; I< user.length();我++){                    JSONObject的C = user.getJSONObject(I)
                    //存放在变量JSON项目
                    字符串IDT = c.getString(TAG_IDT);
                    字符串IDL = c.getString(TAG_IDL);
                    字符串NAMA = c.getString(TAG_NAMA);
                    字符串alamat = c.getString(TAG_ALAMAT);
                    字符串图像= c.getString(TAG_IMAGE);                    // code为获取图像的URL,使字节
                    logoImage = getLogoImage(IMAGEURL +图片);                    databaseHelper.saveCategoryRecord(IDT,IDL,非农产品市场准入,alamat,图像,logoImage);                    //设置JSON数据中的TextView
                // uid.setText(IDT);
                    //name1.setText(name);
                    // email1.setText(电子邮件);
                    //显示在我们的logcat值
                    Log.e(TAG,非农产品市场准入>>>>中+ IDT +alamat>>>>>中+ NAMA);                }
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }
    }
    //尝试获取URL并字节
    私人字节[] getLogoImage(字符串的getURL){
        尝试{
            URL =图片网址新的URL(的getURL);
            URLConnection的UCON = imageUrl.openConnection();            InputStream为= ucon.getInputStream();
            二BufferedInputStream为=新的BufferedInputStream(是);            ByteArrayBuffer BAF =新ByteArrayBuffer(500);
            INT电流= 0;            而((电流= bis.read())!= - 1){
                baf.append((字节)电流);
            }            返回baf.toByteArray();
        }赶上(例外五){
            Log.d(的ImageManager,错误:+ e.toString());
        }
        返回null;
    }}

这是MyDatabase的处理程序

 公共类数据库处理器{
    私有静态最终诠释DATABASE_VERSION = 1;
    私有静态最后弦乐DATABASE_NAME =班图尔;
    私有静态最后弦乐TABLE_NAME =tb_alldata;
    公共静态最后弦乐TAG_IDT =IDT;
    公共静态最后弦乐TAG_IDL =IDL;
    公共静态最后弦乐TAG_NAMA =非农产品市场准入;
    公共静态最后弦乐TAG_ALAMAT =alamat;
    公共静态最后弦乐TAG_IMAGE =形象;
    公共静态最后弦乐TAG_FILE_IMAGE =file_image;    分类openHelper;
    私人SQLiteDatabase数据库;    公共数据库处理器(上下文的背景下){
        openHelper =新类别(背景);
        数据库= openHelper.getWritableDatabase();
    }
    公共无效saveCategoryRecord(IDT字符串,字符串IDL,非农产品市场准入的字符串,字符串alamat,字符串图像,字节[] logoImage){
        ContentValues​​ contentValues​​ =新ContentValues​​();
        contentValues​​.put(TAG_IDT,IDT);
        contentValues​​.put(TAG_IDL,IDL);
        contentValues​​.put(TAG_NAMA,NAMA);
        contentValues​​.put(TAG_ALAMAT,alamat);
        contentValues​​.put(TAG_IMAGE,图像);
        contentValues​​.put(TAG_FILE_IMAGE,logoImage);        database.insert(TABLE_NAME,空,contentValues​​);
        }
    公共光标getTimeRecordList(){
        返回database.rawQuery(SELECT * FROM+ TABLE_NAME,NULL);
        }    私有类范畴扩展SQLiteOpenHelper {        公共类别(上下文的背景下){
            // TODO自动生成构造函数存根
            超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
        }        @覆盖
        公共无效的onCreate(SQLiteDatabase DB){
            // TODO自动生成方法存根
            db.execSQL(CREATE TABLE+ TABLE_NAME +(
                    + TAG_IDT +INTEGER PRIMARY KEY
                    + TAG_IDL +INTEGER,+ TAG_NAMA +TEXT+ TAG_ALAMAT +TEXT+ TAG_IMAGE +TEXT
                    + TAG_FILE_IMAGE +BLOB,));
        }        @覆盖
        公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
            // TODO自动生成方法存根
            db.execSQL(DROP TABLE IF EXISTS+ TABLE_NAME);
            的onCreate(DB);
        }    }


解决方案

这是不完全的回答你的问题:虽然可以做到这一点,它可能是一个坏主意。

SQLite的效率取决于一页的概念。你可以保持引用单个页面越多,越好您的数据库将执行

当你开始使用的BLOB,有可能性,不仅单个行不完全在一个页面上,但单一的BLOB可能不是一个单一页面上。这将显着慢的访问时间。

您可以设置页面大小,但需要的内存手。

如果您的必须的保持图像的数据库,我建议你让他们在一个的独立的数据库。设置页面大小默认的主数据库,并适合于其他的BLOB大小。存储BLOB的PK在主数据库中。

更重要的是,只要保存图像文件系统上,随机名称,名称存储在主数据库。 ContentProviders甚至支持中openFile方法,使这很容易。

您code实际上看起来是正确的。也许这是一些简单的TAG_FILE_GAMAR!= TAG_FILE_IMAGE?

sorry, i'm new in adnroid programming , i try combination JSONParse and sqlite, when i store (insert) data to sqlite my column image = null (not save in sqlite), how to get image from url and store(insert) to sqlite ?

this is my code main activity

public class MainActivity extends Activity {

    Button Btngetdata;

    // URL to get JSON Array
    private static String url = "http://10.0.2.2:81/bantulfolder/alldata.php";

    private String IMAGEURL = "http://10.0.2.2:81/bantulfolder/";

    private byte[] logoImage;

    // JSON Node Names
    private static final String TAG_DATA = "data";
    public static final String TAG_IDT = "idt";
    public static final String TAG_IDL = "idl";
    public static final String TAG_NAMA = "nama";
    public static final String TAG_ALAMAT = "alamat";
    public static final String TAG_IMAGE = "image";

    JSONArray user = null;

    private DatabaseHandler databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper = new DatabaseHandler(MainActivity.this);

        Btngetdata = (Button) findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONParse().execute();
            }
        });
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        final String TAG = "AsyncTaskParseJson.java";
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();
            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                // Getting JSON Array
                user = json.getJSONArray(TAG_DATA);
                // loop through all users
                for (int i = 0; i < user.length(); i++) {

                    JSONObject c = user.getJSONObject(i);
                    // Storing JSON item in a Variable
                    String idt = c.getString(TAG_IDT);
                    String idl = c.getString(TAG_IDL);
                    String nama = c.getString(TAG_NAMA);
                    String alamat = c.getString(TAG_ALAMAT);
                    String image = c.getString(TAG_IMAGE);

                    // code for get image url and make byte
                    logoImage = getLogoImage(IMAGEURL+image);

                    databaseHelper.saveCategoryRecord(idt, idl, nama, alamat, image, logoImage);

                    // Set JSON Data in TextView
                //  uid.setText(idt);
                    //name1.setText(name);
                    // email1.setText(email);
                    // show the values in our logcat
                    Log.e(TAG, "nama >>>> " + idt + "  alamat>>>>> " + nama);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // try get url and make byte
    private byte[] getLogoImage(String geturl) {
        try {
            URL imageUrl = new URL(geturl);
            URLConnection ucon = imageUrl.openConnection();

            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;

            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            return baf.toByteArray();
        } catch (Exception e) {
            Log.d("ImageManager", "Error: " + e.toString());
        }
        return null;
    }

}

and this is mydatabase handler

public class DatabaseHandler {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "bantul";
    private static final String TABLE_NAME = "tb_alldata";
    public static final String TAG_IDT = "idt";
    public static final String TAG_IDL = "idl";
    public static final String TAG_NAMA = "nama";
    public static final String TAG_ALAMAT = "alamat";
    public static final String TAG_IMAGE = "image";
    public static final String TAG_FILE_IMAGE = "file_image";

    Category openHelper;
    private SQLiteDatabase database;

    public DatabaseHandler(Context context){
        openHelper = new Category(context);
        database = openHelper.getWritableDatabase();
    }
    public void saveCategoryRecord(String idt, String idl, String nama, String alamat, String image, byte[] logoImage) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(TAG_IDT, idt);
        contentValues.put(TAG_IDL, idl);
        contentValues.put(TAG_NAMA, nama);
        contentValues.put(TAG_ALAMAT, alamat);
        contentValues.put(TAG_IMAGE, image);
        contentValues.put(TAG_FILE_IMAGE, logoImage);

        database.insert(TABLE_NAME, null, contentValues);
        }
    public Cursor getTimeRecordList() {
        return database.rawQuery("select * from " + TABLE_NAME, null);
        }

    private class Category extends SQLiteOpenHelper {

        public Category(Context context) {
            // TODO Auto-generated constructor stub
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + TABLE_NAME + "( "
                    + TAG_IDT + " INTEGER PRIMARY KEY, "
                    + TAG_IDL + " INTEGER, "+ TAG_NAMA + " TEXT, "+ TAG_ALAMAT + " TEXT, "+ TAG_IMAGE + " TEXT, "
                    + TAG_FILE_IMAGE + " BLOB, )" );
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);
            onCreate(db);
        }

    }

解决方案

This is not exactly an answer to your question: while it is possible to do this, it is probably a bad idea.

SQLite efficiency depends on the concept of a "page". The more you can keep references to a single page, the better your DB will perform.

When you start using BLOBs, there is the possibility that, not only will a single row not be entirely on a single page, but a single BLOB may not be on a single page. That will dramatically slow access times.

You can set the page size, but that takes lots of memory.

If you must keep the images in a database, I suggest that you keep them in a separate databases. Set the page size default in the primary database and appropriate for your BLOB size in the other. Store the PK of the BLOB in the primary db.

Better yet, just save the images on the file system, with random names, and store the names in the primary DB. ContentProviders even support the openFile method, to make this really easy.

Your code actually looks about right. Perhaps it is something as simple as TAG_FILE_GAMAR != TAG_FILE_IMAGE?

这篇关于如何存储图像从网址到SQLite的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆