无法从sqlite在imageview中插入图像

时间:2017-08-13 05:46:16

标签: android sqlite imageview android-sqlite

我的imageview没有填充我选择的图片。请帮助

DBHelper

public class DBHelper {

    public static final String IMAGE_ID = "id";
    public static final String IMAGE = "image";
    private final Context mContext;

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "Images.db";
    private static final int DATABASE_VERSION = 1;

    private static final String IMAGES_TABLE = "ImagesTable";

    private static final String CREATE_IMAGES_TABLE =
            "CREATE TABLE " + IMAGES_TABLE + " (" +
                    IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + IMAGE + " BLOB NOT NULL );";


    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_IMAGES_TABLE);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE);
            onCreate(db);
        }
    }

    public void Reset() {
        mDbHelper.onUpgrade(this.mDb, 1, 1);
    }

    public DBHelper(Context ctx) {
        mContext = ctx;
        mDbHelper = new DatabaseHelper(mContext);
    }

    public DBHelper open() throws SQLException {
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    // Insert the image to the Sqlite DB
    public void insertImage(byte[] imageBytes) {
        ContentValues cv = new ContentValues();
        cv.put(IMAGE, imageBytes);
        mDb.insert(IMAGES_TABLE, null, cv);
    }

    // Get the image from SQLite DB
    // We will just get the last image we just saved for convenience...
    public byte[] retreiveImageFromDB() {
        Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
                null, null, null, null,
                IMAGE_ID + " DESC", "1");
        if (cur.moveToFirst()) {
            byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
            cur.close();
            return blob;
        }
        cur.close();
        return null;
    }
}

ImageFragment

public class ImageFragment extends Fragment {

    private FloatingActionButton floatingActionButton;
    private RecyclerView recyclerView;
    private TextView textView;
    private static int RESULT_LOAD_IMAGE = 1;
    private static int RESULT_CAPTURE_IMAGE = 2;
    TaskCursorImageAdapter myListCursorAdapter;
    public Uri mCurrentTaskUri;
    DBHelper dbHelper;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image, container, false);
        floatingActionButton = (FloatingActionButton) view.findViewById(R.id.fragmentimagefloatingactionbutton);
        recyclerView = (RecyclerView) view.findViewById(R.id.fragmentimagerecyclerview);
        textView = (TextView) view.findViewById(R.id.fragmentimagetextview);

        dbHelper = new DBHelper(getActivity());
        myListCursorAdapter = new TaskCursorImageAdapter(getActivity(), null);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(myListCursorAdapter);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(getActivity(), floatingActionButton);
                //Inflating the Popup using xml file
                popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        if(item.getItemId()==R.id.takephoto){

                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            startActivityForResult(intent, RESULT_CAPTURE_IMAGE);

                        }else if(item.getItemId()==R.id.chooseimage){

                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
                        }

                        return true;
                    }
                });

                popup.show();//showing popup menu
            }
        });


        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {

                // Saving to Database...
                if (saveImageInDB(selectedImageUri)) {
                   Toast.makeText(getActivity(),"Image Saved in Database...",Toast.LENGTH_LONG).show();
                    mCurrentTaskUri=selectedImageUri;


                }

                // Reading from Database after 3 seconds just to show the message
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (loadImageFromDB()) {
                            Toast.makeText(getActivity(),"Image Loaded from Database...",Toast.LENGTH_LONG).show();
                        }
                    }
                }, 3000);
            }

        }


        if (requestCode == RESULT_CAPTURE_IMAGE && resultCode == RESULT_OK && null != data) {

            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img.jpg");

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    Boolean saveImageInDB(Uri selectedImageUri) {

        try {
            dbHelper.open();
            InputStream iStream = getActivity().getContentResolver().openInputStream(selectedImageUri);
            byte[] inputData = Utils.getBytes(iStream);
            dbHelper.insertImage(inputData);
            dbHelper.close();
            return true;
        } catch (IOException ioe) {
            Log.e(TAG, "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
            dbHelper.close();
            return false;
        }

    }

    Boolean loadImageFromDB() {
        try {
            dbHelper.open();
            byte[] bytes = dbHelper.retreiveImageFromDB();
            dbHelper.close();
            // Show Image from DB in ImageView

            return true;
        } catch (Exception e) {
            Log.e(TAG, "<loadImageFromDB> Error : " + e.getLocalizedMessage());
            dbHelper.close();
            return false;
        }
    }


}

TaskCursorImageAdapter

public class TaskCursorImageAdapter extends RecyclerCursorAdapter<TaskCursorImageAdapter.ViewHolder> {
    Context context;
    Cursor cursor;


    public TaskCursorImageAdapter(Context context, Cursor cursor){
        super(context,cursor);
        this.cursor=cursor;
        this.context=context;

    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView imageView;
        Context context;
        Cursor cursor;

        public ViewHolder(View view, Context context, Cursor cursor) {
            super(view);
            this.context = context;
            this.cursor = cursor;
            imageView=(ImageView) view.findViewById(R.id.listitemimageview);

        }


    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
        View view= layoutInflater.inflate(R.layout.list_item_images,parent,false);
        return new ViewHolder(view,context,cursor);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {

      /*  int taskColumnIndex=cursor.getColumnIndex(TaskContract.TaskEntry.NAME_IMAGES);


        String task=cursor.getString(taskColumnIndex);

        viewHolder.cursor = cursor;
        Picasso.with(context).load(task).into(viewHolder.imageView);*/

        DBHelper dbHelper= new DBHelper(context);
        byte[] bytes = dbHelper.retreiveImageFromDB();
        dbHelper.close();
        // Show Image from DB in ImageView
        ImageFragment imageFragment=new ImageFragment();

       // viewHolder.imageView.setImageURI(imageFragment.mCurrentTaskUri);
        viewHolder.imageView.setImageBitmap(Utils.getImage(bytes));
        Toast.makeText(context,"Pritish",Toast.LENGTH_LONG).show();

    }
}

的Utils

public class Utils {

    public static byte[] getImageBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }

    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

}

我的mainactivity中有一个带有图像选项的导航抽屉,点击它后,它会打开ImageFragment,它有一个浮动按钮&amp;单击它会显示一个弹出菜单,显示是否拍摄图像或浏览用户手机的图像。当我浏览手机并选择图像时,图像存储在sqlite中,但不会显示在imageview中

0 个答案:

没有答案