How to progress into saving the image into SQLiteDatabase

Viewed 52

This is where I import the image to(from gallery) and I want to save it to SQLite to hopefully display it in another activity, how would I go about doing so? I am kind of new to Android Studio so if there is some newbie kind of easy way that I would go about doing so would be very helpful. (Update) So I have added this two lines marked by /* */ but now I can't get my app to work still have no idea how to do this.. any ideas?

Import image>Save to SQLite>Take Image to SQLite>Display in another activity

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DataInput extends AppCompatActivity {

    private EditText inputName;
    private EditText inputAge;
    private Button buttonSave;
    private Button buttonGetLocation;

    private Button buttonImportImage;
    private ImageView mImageView;

    private static final int IMAGE_PICK_CODE = 1000;
    private static final int PERMISSION_CODE = 1001;

    private InputHelper helper = null;

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

        inputName = (EditText) findViewById(R.id.input_name);
        inputAge = (EditText) findViewById(R.id.input_age);
        address = (TextView) findViewById(R.id.address);
        buttonSave = findViewById(R.id.button_save);
        buttonSave.setOnClickListener(onSave);

        buttonImportImage = findViewById(R.id.button_import_image);
        mImageView = findViewById(R.id.image_view);
        buttonImportImage.setOnClickListener(onImport);

        helper = new InputHelper(this); }

    private View.OnClickListener onSave = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String nameStr = inputName.getText().toString();
            String ageStr = inputAge.getText().toString();
            String addressStr = address.getText().toString();

            String combineStr = nameStr + "\n" + ageStr + "\n" + addressStr;
            Toast.makeText(v.getContext(), combineStr, Toast.LENGTH_LONG).show();

/*BitmapDrawable drawable = (BitmapDrawable)mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
byte[] image = getBitmapAsByteArray(bitmap);*/

            Intent i = new Intent(DataInput.this,InformationDisplay.class);
            startActivity(i);

            helper.insert(nameStr,ageStr,addressStr,image);

            finish();
        }

  /*  public byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray(); */
    }
};


    private View.OnClickListener onImport = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //check runtime permission
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_DENIED) {
                    //permission not granted, request it.
                    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                    //show popup for runtime permission
                    requestPermissions(permissions, PERMISSION_CODE);
                } else {
                    //permission already granted
                    pickImageFromGallery();
                }
            } else {
                //system os is less then marshmallow
                pickImageFromGallery();
            }
        }
    };

    private void pickImageFromGallery() {
        //intent to pick image
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_PICK_CODE);
    }

    //handle result of runtime permission
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_CODE: {
                if (grantResults.length > 0 && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED) {
                    //permission was granted
                    pickImageFromGallery();
                } else {
                    //permission was denied
                    Toast.makeText(this, "Permission denied...!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    //handle  result of picked image

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
            //set image to image view
            mImageView.setImageURI(data.getData());
        }
    }
1 Answers

You can save an Image in SQLite database in the form of blob. Another simple way to storing the image is in the form of base64 string. This is what I tried in my previous project and this works:

public class Profile_Class extends AppCompatActivity {

private Bitmap photo, OutImage;
private AppPreferences preferences;
private CircularImageView imageView;

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

    EditText name = findViewById(R.id.name);
    preferences = new AppPreferences(this);
    Toolbar toolbar = findViewById(R.id.toolbar_t);
    EditText userName = findViewById(R.id.userName);
    EditText passWord = findViewById(R.id.passWord);
    imageView = findViewById(R.id.iv_profile_auditor);
    ImageView take_pic1 = findViewById(R.id.take_pic1);

    if (prefernces.getProfileImage().equals(" ")) {
        Log.e("TAG", "NoProfilePic");
    } else {
        imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
    }

    take_pic1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        photo = (Bitmap) data.getExtras().get("data");
        OutImage = Bitmap.createScaledBitmap(photo, 300, 400, true);
        
        prefernces.setProfileImage(encodeTobase64(OutImage));
        Intent intent2 = new Intent("header_pic_update");
        LocalBroadcastManager.getInstance(Profile_Class.this).sendBroadcast(intent2);
    }
}

// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    Log.d("Image Log:", imageEncoded);
    return imageEncoded;
}

// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory
            .decodeByteArray(decodedByte, 0, decodedByte.length);
}

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
    }
    return true;
}

If you see in OnActivityResult class, I'm converting the outImage into Base64 string. Here use the method encodeTobase64 and add the image string to your table.

Now in the other activity where you want to show the image, call the method decodeBase64 and decode the image. In the above code I'm decoding the string to image and setting it to imageview like this:

imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));

There are numerous ways to store and retrieve the image. This is one way I did. Mind here that I'm storing the image in bitmap so the quality will not be good. If you want image with full quality than you have to use URI to store the image in your mobile and then call the image in required quality.

Related