将多个图像URL存储为sqlite作为blob

时间:2011-10-14 10:39:54

标签: android image sqlite url

我想在SQLite中存储多个url作为blob。 下面的代码就是我现在所拥有的,但这只是将sqlite中的url转换为图像。有人可以帮我这个吗?

database.java

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteCursorDriver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQuery;
import android.util.Log;

/**
 * Provides access to the vvz4 database. Since this is not a Content Provider,
 * no other applications will have access to the database.
 */
public class VVZ4Database extends SQLiteOpenHelper {
    /** The name of the database file on the file system */
    private static final String DATABASE_NAME = "vvz4";
    /** The version of the database that this class understands. */
    private static final int DATABASE_VERSION = 1;
    /** Keep track of context so that we can load SQL from string resources */
    private final Context mContext;

    static final String LOG_TAG = "VVZ4";


    // #######################################################################################
    // #######################################################################################
    /** Constructor */
    public VVZ4Database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.mContext = context;

    }

    /**
     * Execute all of the SQL statements in the String[] array
     * 
     * @param db
     *            The database on which to execute the statements
     * @param sql
     *            An array of SQL statements to execute
     */
    private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
        for (String s : sql)
            if (s.trim().length() > 0)
                db.execSQL(s);
    }

    /** Called when it is time to create the database */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String[] sql = mContext.getString(R.string.VVZ4Database_onCreate)
                .split("\n");
        db.beginTransaction();
        try {
            // Create tables & test data
            execMultipleSQL(db, sql);
            db.setTransactionSuccessful();
        } catch (SQLException e) {
            Log.e("Error creating tables and debug data", e.toString());
        } finally {
            db.endTransaction();
        }
    }

    /** Called when the database must be upgraded */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(VVZ4Database.LOG_TAG, "Upgrading database from version "
                + oldVersion + " to " + newVersion
                + ", which will destroy all old data");

        String[] sql = mContext.getString(R.string.VVZ4Database_onUpgrade)
                .split("\n");
        db.beginTransaction();
        try {
            // Create tables & test data
            execMultipleSQL(db, sql);
            db.setTransactionSuccessful();
        } catch (SQLException e) {
            Log.e("Error creating tables and debug data", e.toString());
        } finally {
            db.endTransaction();
        }

        // This is cheating. In the real world, you'll need to add columns, not
        // rebuild from scratch
        onCreate(db);
    }

    // #######################################################################################
    // ############# SPELERS
    // #############################################################
    public void addSpelers(String firstname, String lastname, String age, String wasdienst, String fluitdienst, String phone, String foto) {
        String sql = String.format(
                "INSERT INTO spelers (firstname, lastname, age, wasdienst, fluitdienst, phone, foto) "
                        + "VALUES ( %s, %s, %s, %s, %s , %s, %s)",
                DatabaseUtils.sqlEscapeString(firstname),
                DatabaseUtils.sqlEscapeString(lastname),
                DatabaseUtils.sqlEscapeString(age),
                DatabaseUtils.sqlEscapeString(wasdienst),
                DatabaseUtils.sqlEscapeString(fluitdienst),
                DatabaseUtils.sqlEscapeString(phone),
                DatabaseUtils.sqlEscapeString(foto));
        try {
            getWritableDatabase().execSQL(sql);
        } catch (SQLException e) {
            Log.e("Error writing new spelers", e.toString());
        }
    }   
    // 
    // ################ SPELERS
    // ################################################################
    public void deleteAllSpelers() {
        String sql = "DELETE from spelers";
        try {
            getWritableDatabase().execSQL(sql);
        } catch (SQLException e) {
            Log.e("Error deleting all spelers", e.toString());
        }
    }   

    // 
    // ################ SPELERS
    // ################################################################
    public SpelersCursor getSpelers() {
        String sql = SpelersCursor.QUERY;
        SQLiteDatabase d = getReadableDatabase();
        SpelersCursor c = (SpelersCursor) d.rawQueryWithFactory(
                new SpelersCursor.Factory(), sql, null, null);
        c.moveToFirst();
        return c;
    }

    public static class SpelersCursor extends SQLiteCursor {

        private static final String QUERY = "SELECT _id, firstname, lastname, age, wasdienst, fluitdienst, phone, foto "
            + "FROM spelers " + "ORDER BY _id ";

        private SpelersCursor(SQLiteDatabase db, SQLiteCursorDriver driver,
                String editTable, SQLiteQuery query) {
            super(db, driver, editTable, query);
        }

        private static class Factory implements SQLiteDatabase.CursorFactory {
            @Override
            public Cursor newCursor(SQLiteDatabase db,
                    SQLiteCursorDriver driver, String editTable,
                    SQLiteQuery query) {
                return new SpelersCursor(db, driver, editTable, query);
                }
            }

        public String getColFirstname() {
            return getString(getColumnIndexOrThrow("firstname"));
        }

            public String getColLastname() {
                return getString(getColumnIndexOrThrow("lastname"));
            }

            public String getColAge() {
                return getString(getColumnIndexOrThrow("age"));
            }

            public String getColWasdienst() {
                return getString(getColumnIndexOrThrow("wasdienst"));
            }

            public String getColFluitdienst() {
                return getString(getColumnIndexOrThrow("fluitdienst"));
            }

            public String getColPhone() {
                return getString(getColumnIndexOrThrow("phone"));
            }

            public String getColFoto() {
                return getString(getColumnIndexOrThrow("foto"));
            }
        }
}

Activity.java

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vvz4.app.VVZ4Database.SpelersCursor;

//import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
//import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
//import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.util.Linkify;
import android.util.Log;
//import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
//import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
//import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
//import android.widget.LinearLayout;
import android.widget.TextView;

public class SpelersActivity extends ListActivity {

    private final int VVZ4_MAX_SPELERS = 20;
    public static final String KEY_121 = "http://www.vvz4.nl/ripper/vvz4fluiten.php";
    private int iNumSpelers = 0;

    private VVZ4Database VVZ4_database;

    private Handler mHandler = new Handler();

    private ImageButton btnRefresh;

//  private float downXValue;

    public class Vvz4Spelers {
        public String firstname;
        public String lastname;
        public String age;
        public String wasdienst;
        public String fluitdienst;
        public String phone;
        public String foto;

        Vvz4Spelers(String firstname, String lastname, String age, String wasdienst, String fluitdienst, String phone, String foto) {
            this.firstname = firstname;
            this.lastname = lastname;
            this.age = age;
            this.wasdienst = wasdienst;
            this.fluitdienst = fluitdienst;
            this.phone = phone;
            this.foto = foto;
        }
    };

    Vvz4Spelers[] spelersListData;
    Vvz4Spelers[] spelersInternetData;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spelers);

        // setTitle(getString(R.string.wedstrijden));

        VVZ4_database = new VVZ4Database(this);

        btnRefresh = (ImageButton) findViewById(R.id.btnRefresh);

        btnRefresh.setOnClickListener(btnRefreshOnClick);

        // maak een array aan om alle spelers in te zetten
        spelersListData = new Vvz4Spelers[VVZ4_MAX_SPELERS];
        spelersInternetData = new Vvz4Spelers[VVZ4_MAX_SPELERS];

        // zet spelers uit database in list
        FillListFromDB();

        // probeer ook nieuwe spelers info op te halen
        mHandler.postDelayed(mInternetTask, 1000);

        getListView().setDividerHeight(2);

        //getListView().setOnTouchListener(this);
    }

    private final ImageButton.OnClickListener btnRefreshOnClick = new ImageButton.OnClickListener() {
        @Override
        public void onClick(View v) {
            mHandler.postDelayed(mInternetTask, 100);
        }
    };

    private void FillListFromDB() {

        // wissen array
        for (int i = 0; i < VVZ4_MAX_SPELERS; i++) {
            spelersListData[i] = new Vvz4Spelers("", "", "", "", "", "", "");
        }

        // open cursor om door alle records heen te lopen
        SpelersCursor wC = VVZ4_database.getSpelers();

        Log.e("---->VVZ4 aantal wedstrijd records in database: ",
                String.format("%d", wC.getCount()));

        // vul array met data uit database
        int iRecord = 0;
        while (!wC.isAfterLast()) {

            if (iRecord >= VVZ4_MAX_SPELERS) {
                break;
            } // array is full

            spelersListData[iRecord].firstname = wC.getColFirstname();
            spelersListData[iRecord].lastname = wC.getColLastname();
            spelersListData[iRecord].age = wC.getColAge();
            spelersListData[iRecord].wasdienst = wC.getColWasdienst();
            spelersListData[iRecord].fluitdienst = wC.getColFluitdienst();
            spelersListData[iRecord].phone = wC.getColPhone();
            spelersListData[iRecord].foto = wC.getColFoto();

            iRecord++;

            // volgende record uit database
            wC.moveToNext();
        }
        iNumSpelers = iRecord;

        // close cursor
        wC.close();

        setListAdapter(new Vvz4SpelersDataAdapter(this));
    }

    private void LoadSpelersFromInternet() {

        // wissen array
        for (int i = 0; i < VVZ4_MAX_SPELERS; i++) {
            spelersInternetData[i] = new Vvz4Spelers("", "", "", "", "", "", "");
        }

        // haal de php data op
        String phpString = getServerData(SpelersActivity.KEY_121);

        int iNumLoadedFromInternet = 0;

        // parse json data
        try {
            JSONArray jArray = new JSONArray(phpString);
            int i = 0;
            for (i = 0; i < jArray.length(); i++) {
                if (i >= VVZ4_MAX_SPELERS) {
                    break;
                } // array is full
                JSONObject json_data = jArray.getJSONObject(i);
                String strFirstname = json_data.getString("firstname");
                String strLastname = json_data.getString("lastname");
                String strAge = json_data.getString("age");
                String strWasdienst = json_data.getString("wasdienst");
                String strFluitdienst = json_data.getString("fluitdienst");
                String strPhone = json_data.getString("phone");
                String strFoto = json_data.getString("foto");
                spelersInternetData[i].firstname = strFirstname;
                spelersInternetData[i].lastname = strLastname;
                spelersInternetData[i].age = strAge;
                spelersInternetData[i].wasdienst = strWasdienst;
                spelersInternetData[i].fluitdienst = strFluitdienst;
                spelersInternetData[i].phone = strPhone;
                spelersInternetData[i].foto = strFoto;
            }
            iNumLoadedFromInternet = i;
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        // alleen als er werkelijk spelers data van internet is geladen
        if (iNumLoadedFromInternet > 0) {

            // wis alle spelers records uit database
            VVZ4_database.deleteAllSpelers();
            Log.e("---->VVZ4 ", "Wissen alle spelers...");

            // vul database opnieuw
            for (int i = 0; i < iNumLoadedFromInternet; i++) {
                VVZ4_database.addSpelers(spelersInternetData[i].firstname, spelersInternetData[i].lastname, spelersInternetData[i].age, spelersInternetData[i].wasdienst,
                        spelersInternetData[i].fluitdienst, spelersInternetData[i].phone, spelersInternetData[i].foto);
                Log.e("---->VVZ4 Toevoegen wedstrijd: ", String.format(
                        "%s,%s,%s,%s,%s,%s, %s", spelersInternetData[i].firstname, spelersInternetData[i].lastname, spelersInternetData[i].age, spelersInternetData[i].wasdienst,
                        spelersInternetData[i].fluitdienst, spelersInternetData[i].phone, spelersInternetData[i].foto));
            }

            FillListFromDB();
        }
    }

    public class Vvz4SpelersDataAdapter extends BaseAdapter {
        private Context context;

        public Vvz4SpelersDataAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return iNumSpelers;
        }

        @Override
        public Object getItem(int position) {

            return spelersListData[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }



        /**
         * Custom view translates columns into appropriate text, images etc.
         * 
         * (non-Javadoc)
         * 
         * @see android.widget.CursorAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View v = convertView;
            if (v == null) {
                // sender is activity from where you call this adapter. Set it
                // with construktor.
                LayoutInflater vi = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.spelersrow, null);
            }

            Vvz4Spelers item = (Vvz4Spelers) getItem(position);

            //LinearLayout llRow = (LinearLayout) v.findViewById(R.id.llRow);
            TextView tvfirstname = (TextView) v.findViewById(R.id.lblFirstname);
            TextView tvlastname = (TextView) v.findViewById(R.id.lblLastname);
            TextView tvage = (TextView) v.findViewById(R.id.lblAge);
            TextView tvwasdienst = (TextView) v.findViewById(R.id.lblWasdienst);
            TextView tvfluitdienst = (TextView) v.findViewById(R.id.lblFluitdienst);
            TextView tvphone = (TextView) v.findViewById(R.id.lblPhone);
            ImageView tvfoto = (ImageView) v.findViewById(R.id.lblFoto);


            if (tvfirstname != null) {
                tvfirstname.setText(String.format("%s", item.firstname));
            }

            if (tvlastname != null) {
                tvlastname.setText(String.format("%s", item.lastname));
            }

            if (tvage != null) {
                tvage.setText(String.format("%s", item.age));
            }

            if (tvwasdienst != null) {
                tvwasdienst.setText(String.format("%s", item.wasdienst));
            }

            if (tvfluitdienst != null) {
                tvfluitdienst.setText(String.format("%s", item.fluitdienst));
            }

            if (tvphone != null) {
                tvphone.setText(String.format("%s", item.phone));
                Linkify.addLinks(tvphone, Linkify.PHONE_NUMBERS);
                tvphone.setLinkTextColor(Color.GREEN);              
            }

            try {
                String url1 = String.format("%s", item.foto);
                URL url = new URL(url1);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                BitmapFactory.Options bfOptions = new BitmapFactory.Options();
                bfOptions.inDither = false; 
                bfOptions.inPurgeable = true; // Tell to gc that whether it needs free memory, the Bitmap can be cleared
                bfOptions.inInputShareable = true; // Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
                bfOptions.inTempStorage = new byte[16 * 1024];
                Bitmap bmp = null;
                bmp = BitmapFactory.decodeStream(input, null,
                        bfOptions);
                tvfoto.setImageBitmap(bmp);
                connection.disconnect();
                input.close();

            } catch (MalformedURLException e) {
            } catch (IOException e) {
            } catch (IllegalAccessError e) {
            } catch (NullPointerException e) {
            }


            return v;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // boolean supRetVal = super.onCreateOptionsMenu(menu);
        menu.add(1, 1, 0, "Wasdienst").setAlphabeticShortcut('4')
                .setIcon(R.drawable.internet);
        menu.add(1, 2, 1, "Fluitdienst").setAlphabeticShortcut('w')
                .setIcon(R.drawable.texttv);
        menu.add(1, 3, 2, "Home").setAlphabeticShortcut('v')
                .setIcon(R.drawable.internet);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
            startActivity(new Intent(this, VVZ4WebViewActivity.class));
            return true;
        case 2:
            startActivity(new Intent(this, WedstrijdverslagenActivity.class));
            return true;
        case 3:
            startActivity(new Intent(this, VVZ4TabWidget.class));
            return true;
        }

        return false;
    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    public void onPause() {

        super.onPause();
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    /**
     * Make sure to stop the animation when we're no longer on screen, failing
     * to do so will cause a lot of unnecessary cpu-usage!
     */
    @Override
    public void onSaveInstanceState(Bundle icicle) {
        super.onSaveInstanceState(icicle);
    }

    private String getServerData(String returnString) {

        String result = "";
        // the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // nameValuePairs.add(new BasicNameValuePair("team","VVZ"));

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, HTTP.ISO_8859_1);

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        return result;
    }


    private Runnable mInternetTask = new Runnable() {
        @Override
        public void run() {

            LoadSpelersFromInternet();

        }
    };


}

的strings.xml

    <string name="VVZ4Database_onCreate">"
CREATE TABLE wedstrijden (_id INTEGER PRIMARY KEY AUTOINCREMENT, datum TEXT, tijd TEXT, wedstrijd TEXT);
CREATE TABLE uitslagen (_id INTEGER PRIMARY KEY AUTOINCREMENT, datum TEXT, thuis TEXT, uit TEXT, uitslag TEXT);
CREATE TABLE stand (_id INTEGER PRIMARY KEY AUTOINCREMENT, plaats TEXT, elftal TEXT, g TEXT, w TEXT, gw TEXT, v TEXT, p TEXT, dpv TEXT, dpt TEXT, pm TEXT);
CREATE TABLE spelers (_id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT, age TEXT, wasdienst TEXT, fluitdienst TEXT, phone TEXT, foto BLOB);
"</string>
<string name="VVZ4Database_onUpgrade">"
DROP TABLE IF EXISTS wedstrijden
DROP TABLE IF EXISTS uitslagen
DROP TABLE IF EXISTS stand
DROP TABLE IF EXISTS spelers
"</string>  

1 个答案:

答案 0 :(得分:1)

首先:如果您只想存储图片网址,则无需使用blob

第二:如果你想将图像存储在数据库中,那么你必须首先下载图像然后将其转换为位图然后转换为字节数组。然后从数据库获取然后相同的反向必须遵循程序

Code:  Download image from image_url
DataBaseHelper db=new DataBaseHelper(this);  //Contain  table
    SQLiteDatabase db1=db.getWritableDatabase();
    Bitmap bitmap=BitmapFactory.decodeResource(this.getResources(),R.drawable.steve_jobs_tribute_feeldesain_021 );
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, bos);
    byte [] b=bos.toByteArray();
    ContentValues cv=new ContentValues();
    cv.put(DataBaseHelper.Col1,b);

    int i=(int) db1.insert(DataBaseHelper.Table1, null,cv);  //saving image
    if(i!=-1){
        Toast.makeText(this,"Image Inserted",Toast.LENGTH_LONG).show();
        Cursor cur=db1.query(DataBaseHelper.Table1, null,null,null,null,null, null);
        cur.moveToFirst();
        byte [] b1=cur.getBlob(0);              // fetching image
       //ByteArrayInputStream bos1=new ByteArrayInputStream(b1s);
        Bitmap bitmap2=BitmapFactory.decodeByteArray(b1, 0, b1.length);
        img.setImageBitmap(bitmap2);
    }
    }
    catch(Exception e){
        e.getMessage();
    }

现在制作代码 String str= "create table Table1("+Col1+" blob not null);"; db.execSQL(str);