0

I have a database app. It shows a list of items containing an image and strings. I want to store image in sqlite database in an activity and fetch it from another activity. But it shows null value is inserted. Here is the code for insertion of images in database---

public class EditorActivity extends AppCompatActivity  implements View.OnClickListener{

    private static int IMAGE_GALLERY_REQUEST=20;
    private EditText mNameEditText;
    private EditText mDescEditText;
    private EditText mResEditText;
    private EditText mStatusEditText;
    private Button btn;
    private byte[] b;
    private Bitmap bitmap;
    String mName,mDescription,mResident,mStatus;
    int data;
    public static String EXTRA_DATA="dataNo";

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

        mNameEditText = (EditText) findViewById(R.id.name);
        mDescEditText = (EditText) findViewById(R.id.desc);
        mResEditText = (EditText) findViewById(R.id.res);
        mStatusEditText = (EditText) findViewById(R.id.status);
        btn=findViewById(R.id.photo);

        btn.setOnClickListener(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            data = (Integer) (bundle.get(EXTRA_DATA));
        }

    }

    private void saveData()
    {
        mName=mNameEditText.getText().toString().trim();
        mDescription=mDescEditText.getText().toString().trim();
        mResident=mResEditText.getText().toString().trim();
        mStatus=mStatusEditText.getText().toString().trim();

        FriendsDbHelper helper=new FriendsDbHelper(this);
        SQLiteDatabase db=helper.getWritableDatabase();
        ContentValues values=new ContentValues();

        values.put(FriendContract.FriendEntry.NAME,mName);
        values.put(FriendContract.FriendEntry.DESCRIPTION,mDescription);
        values.put(FriendContract.FriendEntry.RESIDENCE,mResident);
        values.put(FriendContract.FriendEntry.STATUS,mStatus);
        values.put(FriendContract.FriendEntry.KEY_IMAGE,b);


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.menu_edit,menu);
       return true;
    }

    public void updateData() {

        String name=mNameEditText.getText().toString().trim();
        String description=mDescEditText.getText().toString().trim();
        String resident=mResEditText.getText().toString().trim();
        String status=mStatusEditText.getText().toString().trim();

        //try{

        FriendsDbHelper helper = new FriendsDbHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();

        if(TextUtils.isEmpty(name))
        {
            name=mName;
        }
        if(TextUtils.isEmpty(description))
        {
            description=mDescription;
        }
        if(TextUtils.isEmpty(resident))
        {
            resident=mResident;
        }
        if(TextUtils.isEmpty(status))
        {
            status=mStatus;
        }

        values.put(NAME, name);
        values.put(DESCRIPTION, description);
        values.put(RESIDENCE, resident);
        values.put(STATUS, status);

        db.update(TABLE_NAME, values, _ID + "=?", new String[]{Integer.toString(data)});
   /* }
        catch (SQLiteException e)
        {
            Toast.makeText(this,"Update failed",Toast.LENGTH_LONG).show();
        }*/
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_save:
                saveData();
                finish();
                return true;
            case R.id.action_update:
                updateData();
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        Intent photoIntent=new Intent(Intent.ACTION_PICK);
        File photoDirectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String photo=photoDirectory.getPath();
        Uri uri=Uri.parse(photo);

        photoIntent.setDataAndType(uri,"image/*");

        startActivityForResult(photoIntent,IMAGE_GALLERY_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==RESULT_OK)
        {
            if(resultCode==IMAGE_GALLERY_REQUEST)
            {
                Uri uri=data.getData();
                InputStream inputStream;
                try
                {
                    inputStream=getContentResolver().openInputStream(uri);
                    bitmap= BitmapFactory.decodeStream(inputStream);
                    ByteArrayOutputStream stream=new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG,0,stream);
                    b=stream.toByteArray();
                }
                catch (FileNotFoundException e)
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"Unable to open image",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

As a result, strings in each element is visible but image is not visible.

I read same problem from Insert bitmap to sqlite database. They told to use sqlitemaestro software. How to use that in android?

Please reply soon.

2 Answers2

0

It seems as if the Byte array 'b' is null when you are using the values.put in the savedata method kindly log the variable and check.

Also to save image in SQLite we usually make use of Binary Large Objects i.e BLOBs

Here is a resource which may help you How to store(bitmap image) and retrieve image from sqlite database in android?

Raj Saraogi
  • 1,780
  • 1
  • 13
  • 21
  • When using the convenience `insert` method the appropriate type will be determined according to the type of the value (as per the `ContentValues` object) i.e. if using `values.put(column,data)`, if **data** is of type `byte[]` it will be stored as a BLOB (irrespective of the defined column type (affinity)). Likewise `NULL` will always be stored as a `NULL` (constraints permitting). [Datatypes In SQLite Version 3 - Storage Classes and Datatypes](https://sqlite.org/datatype3.html) – MikeT Feb 11 '18 at 01:07
0

Using a cutdown version of your code. There appears to be nothing wrong with the SQLite side. That is using :-

public class MainActivity extends AppCompatActivity  implements View.OnClickListener {

    private static int IMAGE_GALLERY_REQUEST = 20;
    private EditText mNameEditText;
    private EditText mDescEditText;
    private EditText mResEditText;
    private EditText mStatusEditText;
    private Button btn;
    private byte[] b;
    private Bitmap bitmap;
    String mName, mDescription, mResident, mStatus;
    int data;
    public static String EXTRA_DATA = "dataNo";

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

        mNameEditText = (EditText) findViewById(R.id.name);
        mDescEditText = (EditText) findViewById(R.id.desc);
        mResEditText = (EditText) findViewById(R.id.res);
        mStatusEditText = (EditText) findViewById(R.id.status);
        btn = findViewById(R.id.photo);

        btn.setOnClickListener(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            data = (Integer) (bundle.get(EXTRA_DATA));
        }
    }

    private void saveData() {
        mName = mNameEditText.getText().toString().trim();
        mDescription = mDescEditText.getText().toString().trim();
        mResident = mResEditText.getText().toString().trim();
        mStatus = mStatusEditText.getText().toString().trim();

        FriendsDbHelper helper = new FriendsDbHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(FriendsDbHelper.COL_FRIENDS_NAME, mName);
        values.put(FriendsDbHelper.COL_FRIENDS_DESCRIPTION, mDescription);
        values.put(FriendsDbHelper.COL_FRIENDS_RESIDENCE, mResident);
        values.put(FriendsDbHelper.COL_FRIENDS_STATUS, mStatus);
        values.put(FriendsDbHelper.COL_FRIENDS_KEY_IMAGE, b);


        db.insert(FriendsDbHelper.TB_FRIENDS, null, values);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == btn.getId()) {
            b = new byte[]{0,2,3,4,5,6,7,8,9};
            saveData();
        }

    }
}

Saves a BLOB as expected, as per :-

enter image description here

  • i.e. the last column is the array of bytes ( the elements being 0,2,3,4,5,6,7,8,9) shown as hex representation as was expected.
  • This therefore rules out any issue with the SQLite aspect and therefore indicates that the issue is that b is not being set accordingly in the onActivityResult method, which itself relies upon the intent.ACTION_PICK.

You may wish to refer to opening an image using Intent.ACTION_PICK (see notes re returning null) and perhaps Intent.ACTION_PICK behaves differently or the many other SO questions regarding intent.ACTION_PICK.

You may also wish to use something like :-

private void saveData()
{
    mName=mNameEditText.getText().toString().trim();
    mDescription=mDescEditText.getText().toString().trim();
    mResident=mResEditText.getText().toString().trim();
    mStatus=mStatusEditText.getText().toString().trim();

    FriendsDbHelper helper=new FriendsDbHelper(this);
    SQLiteDatabase db=helper.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(FriendContract.FriendEntry.NAME,mName);
    values.put(FriendContract.FriendEntry.DESCRIPTION,mDescription);
    values.put(FriendContract.FriendEntry.RESIDENCE,mResident);
    values.put(FriendContract.FriendEntry.STATUS,mStatus);
    values.put(FriendContract.FriendEntry.KEY_IMAGE,b);

    //<<<< ADDED to issue Toast if no valid image...
    if (b == null) {
        Toast.makeText(this,"No valid Image - No Data Stored!",Toast.LENGTH_LONG).show();
        return;
    }

    db.insert(TABLE_NAME,null,values);
}
MikeT
  • 51,415
  • 16
  • 49
  • 68