从url到数据库SQLite Android获取图片

时间:2015-12-28 12:53:10

标签: java android sqlite bitmap blob

所以,我有一个从url下载图像并将其传输到byte []的方法。然后,我把那个byte []放到我的数据库中。我在我的专栏中使用了blob类型,但它给了我一个错误。以下是从url:

下载图像的方法
public static byte[] getByteFromUrl(URL src) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = null;
    try {
        is = src.openStream();
        byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
        int n;

        while ((n = is.read(byteChunk)) > 0) {
            baos.write(byteChunk, 0, n);
        }
        return baos.toByteArray();
    } catch (IOException e) {
        System.err.printf("Failed while reading bytes from %s: %s", src.toExternalForm(), e.getMessage());
        e.printStackTrace();
        // Perform any other exception handling that's appropriate.
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

和插入数据库的方法:

/**
 * Method for adding UserData into local database
 *
 * @param userData object that has all the user data information
 * @param id       id of the user
 */
public void addUserData(UserData userData, long id, byte[] picture) {
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(USER_DATA_ID, id);
    values.put(USER_DATA_FIRST_NAME, userData.getFistName());
    values.put(USER_DATA_LAST_NAME, userData.getLastName());
    values.put(USER_DATA_NICK_NAME, userData.getNickname());
    values.put(USER_DATA_DISPLAY_NAME, userData.getHowPeopleSeeMe());
    values.put(USER_DATA_EMAIL, userData.getEmail());
    values.put(USER_DATA_PHONE_NUMBER, userData.getMobilePhoneNumber());
    values.put(USER_DATA_GENDER, userData.getGender());
    values.put(USER_DATA_RATING, userData.getReliabilityRating());
    values.put(USER_DATA_PASSWORD, userData.getPassword());
    values.put(USER_DATA_PICTURE, picture);

    db.insert(TABLE_USER_DATA, null, values);
}

现在,一切顺利,直到我想从数据库中获取所有内容:

/**
 * Method that fetches user data from local database
 *
 * @return UserData object is returned
 */
public UserData getUserData() {
    UserData userData = new UserData();
    SQLiteDatabase db = getReadableDatabase();
    String selectQuery = "SELECT * FROM " + TABLE_USER_DATA;
    Cursor c = db.rawQuery(selectQuery, null);
    if (c.moveToFirst()) {
        do {
            long id = c.getLong(0);
            userData.setFistName(c.getString(1));
            userData.setLastName(c.getString(2));
            userData.setNickname(c.getString(3));
            userData.setHowPeopleSeeMe(c.getString(4));
            userData.setEmail(c.getString(5));
            userData.setMobilePhoneNumber(c.getString(6));
            userData.setGender(c.getInt(7));
            userData.setPicture(c.getBlob(8) != null ? getImage(c.getBlob(8)) : null);
            userData.setReliabilityRating(c.getInt(9));
            userData.setPassword(c.getString(10));
            return userData;
        } while (c.moveToNext());

    }
    c.close();
    return null;
}

其中getImage方法是:

 /**
 * Method for converting bytes to bitmap
 *
 * @param image bytes[] that we are converting to bitmap
 * @return bitmap image
 */
public Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

我接下来的错误是:

    12-28 13:41:32.348 8057-8057/share.advice.khalifa.adviceshare E/CursorWindow: Failed to read row 0, column 0 from a CursorWindow which has 0 rows, 11 columns.
12-28 13:41:32.349 8057-8057/share.advice.khalifa.adviceshare D/AndroidRuntime: Shutting down VM
12-28 13:41:32.349 8057-8057/share.advice.khalifa.adviceshare E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: share.advice.khalifa.adviceshare, PID: 8057
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{share.advice.khalifa.adviceshare/share.advice.khalifa.adviceshare.ui.activities.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                    at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                    at android.os.Looper.loop(Looper.java:148)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                 Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                                    at android.database.CursorWindow.nativeGetLong(Native Method)
                                                                                    at android.database.CursorWindow.getLong(CursorWindow.java:511)
                                                                                    at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:75)
                                                                                    at share.advice.khalifa.adviceshare.io.SQLDatabase.getUserData(SQLDatabase.java:178)
                                                                                    at share.advice.khalifa.adviceshare.io.model.Model.setUpModel(Model.java:179)
                                                                                    at share.advice.khalifa.adviceshare.ui.activities.MainActivity.onCreate(MainActivity.java:115)
                                                                                    at android.app.Activity.performCreate(Activity.java:6251)
                                                                                    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                    at android.os.Looper.loop(Looper.java:148) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                    at java.lang.reflect.Method.invoke(Native Method) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

3 个答案:

答案 0 :(得分:1)

我不是Android专家,但我对c.getLong(0);有点担心。

Failed to read row 0, column 0 from a CursorWindow which has 0 rows, 11 columns 

你的光标是否返回0行?

答案 1 :(得分:1)

在您将数据插入数据库的updateUserData方法中,我没有看到实际添加到数据库中的图像数据。也许这就是问题?

答案 2 :(得分:0)

好的,所以,你想这样做:

在创建时检查您要放置图片的目录是否存在:

 // DownloadImage AsyncTask
    private class DownloadImage extends AsyncTask<String, Void, byte[]> {

        UserData userData;

        public DownloadImage(UserData userData) {
            this.userData = userData;
        }

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

        @Override
        protected byte[] doInBackground(String... URL) {
            try {
                return ViewUtils.getByteFromUrl(new URL(URL[0]));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            File photo = new File(getCacheDir() + "/profile_picture/", "photo.jpg");
            if (photo.exists()) {
                photo.delete();
            }
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(photo));
                bos.write(result);
                bos.flush();
                bos.close();
            } catch (java.io.IOException e) {
                Log.e("PictureDemo", "Exception in photoCallback", e);
            }

        }

    }

现在,您要在byte []:

中从URL下载Image
ViewUtils.getByteFromUrl(new URL(URL[0]));

其中

public static byte[] getByteFromUrl(URL src) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = src.openStream();
            byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
            int n;

            while ((n = is.read(byteChunk)) > 0) {
                baos.write(byteChunk, 0, n);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            System.err.printf("Failed while reading bytes from %s: %s", src.toExternalForm(), e.getMessage());
            e.printStackTrace();
            // Perform any other exception handling that's appropriate.
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

dnx run &

现在您已成功将图像保存到本地存储。