【问题标题】:Attempt to get length of null array - retrieve bitmap image from sqlite DB尝试获取空数组的长度 - 从 sqlite DB 检索位图图像
【发布时间】:2017-04-06 10:27:48
【问题描述】:

我正在尝试从 SQLite 数据库中检索图像。图像存储为 BLOB,并尝试使用数组检索它。我不确定它为什么这样做。权限都设置正确。

package com.example.joao_.quizathonegroupteamproject.Activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.joao_.quizathonegroupteamproject.DatabaseClasses.User;
import com.example.joao_.quizathonegroupteamproject.R;

import java.util.ArrayList;

/**
 * Created by Quoc Nguyen on 13-Dec-16.
 */

public class UserListAdapter extends BaseAdapter {

    private Context context;
    private  int layout;
    private ArrayList<User> foodsList;

    public UserListAdapter(Context context, int layout, ArrayList<User> foodsList) {
        this.context = context;
        this.layout = layout;
        this.foodsList = foodsList;
    }

    @Override
    public int getCount() {
        return foodsList.size();
    }

    @Override
    public Object getItem(int position) {
        return foodsList.get(position);
    }

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

    private class ViewHolder{
        ImageView imageView;

    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {

        View row = view;
        ViewHolder holder = new ViewHolder();

        if(row == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(layout, null);


            holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
            row.setTag(holder);
        }
        else {
            holder = (ViewHolder) row.getTag();
        }

        User food = foodsList.get(position);

        byte[] tblUsersImage = food.getImage();
        Bitmap bitmap = BitmapFactory.decodeByteArray(tblUsersImage, 0, tblUsersImage.length);
        holder.imageView.setImageBitmap(bitmap);

        return row;
    }
}

【问题讨论】:

  • "I'm not sure why its doing this." 它在做什么,您是否收到特定的错误消息?
  • 如何在数据库中保存和读取位图?
  • 你的数组曾经为空?
  • 你的 food.getImage()` 返回 null

标签: java android arrays


【解决方案1】:

您可以像这样检索 BLOB 图像并将其存储在字节数组中:

byte[] array = cursor.getBlob(columnIndex);  

Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0 ,array.length);

然后将其设置为图像视图

holder.imageView.setImageBitmap(bitmap);

【讨论】:

    【解决方案2】:

    您没有提供您的 SQLite 数据库类,但我认为您的 food.getImage(); 返回空值。

    检查 SQLite 数据库中的 dataInsert 方法或 getData !

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多