3

I’m a newbie developer and I am currently working on an app in which part of the functionality allows users to capture an image, store it in the app’s file system, and store its reference in a column of a SQLite database. The user will then be able to view these images in a gridview based on whatever criteria it is associated with in the database (e.g. only displaying images that are a certain colour).

At first I actually “grabbed” the captured image’s file name and stored that in the database, using this code:

//Initializing Variables:
protected ImageButton _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected String name;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";

@Override
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newitemui);

    //Creating the "item_images" directory and File:
    File dir = new File("sdcard/item_images"); 
    try
    {
        //Create new directory:
        if(dir.mkdir()) 
        {
            System.out.println("Directory created");
        } 
        else 
        {
            System.out.println("Directory is not created");
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    //Setting the current time stamp for image name:
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());

    _image = ( ImageView ) findViewById( R.id.image );
    _field = ( TextView ) findViewById( R.id.field );
    _button = ( ImageButton ) findViewById( R.id.button );
    _button.setOnClickListener( new ButtonClickHandler() );
    name = "IMG_" + timeStamp + ".png";
    _path = Environment.getExternalStorageDirectory() + File.separator + "/item_images" + "/" + name;

    Toast toast = Toast.makeText(NewItemUI.this,"Touch Camera to Capture Image", Toast.LENGTH_LONG);
    toast.show();
    toast.setGravity(Gravity.DISPLAY_CLIP_HORIZONTAL|Gravity.BOTTOM, 0, 200);
}

 public class ButtonClickHandler implements View.OnClickListener 
    {
        public void onClick( View view ){
            startCameraActivity();
        }
    }

 protected void startCameraActivity()
    {
        File file = new File( _path );
        Uri outputFileUri = Uri.fromFile( file );

        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
        intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

        startActivityForResult( intent, 0 ); 
    }


 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {               
        switch( resultCode )
        {
            //If user did not take photo, return to the original screen with no result:
            case 0:
                break;

            //If user took a photo, insert the image name into database and return to the original screen with the captured image displayed:
            case -1:

                    AppDatabase appdb = new AppDatabase(this);
                    SQLiteDatabase sql = appdb.getWritableDatabase();
                    sql.execSQL("INSERT INTO tblClothingItem (imagePath) VALUES ('"+name+"');");
                    sql.close();
                    appdb.close();

                    onPhotoTaken();
                    break;  
        }

    }

However I realized that the filename stored is just an ordinary string in the context of the app and does not actually point to any one image stored in the file system.

What I would like to know is:

  1. How I can store the Uri of an image in my SQLite database as it is captured
  2. How would I go about retrieving thee images based on their stored Uri to display in a gridview.

Any suggestions, sample code, feedback is welcomed.

ImNewHere
  • 45
  • 1
  • 7
  • 1
    Just as you mentioned, URI is actually just a text with specific format. You can store it as `String` (or `TEXT` in SQLite). To get the same URI from the `String`, you can use `Uri.parse()` – Andrew T. Nov 28 '13 at 02:27
  • @AndrewT. thank you for your quick response and suggestion. – ImNewHere Nov 28 '13 at 02:31
  • @AndrewT. if it is just a text, can I use the file names I am already storing in my database and use that to retrieve the images in a gridview? – ImNewHere Nov 28 '13 at 02:34
  • Yes. However, this depends on how you use/create the adapter for the `GridView`. These are some possible cases that I have thought: 1) storing only the file name without full path (assuming all the images have a common root), 2) storing the full path+file name, 3) storing the URI. All these cases are possible, the real question is how to use the data in the adapter... I hope this gives you insight :) – Andrew T. Nov 28 '13 at 03:35
  • @AndrewT. That is indeed the question and something that I am going to look into. The images I am capturing are stored in the same folder so I believe your first suggestion (which is what my code currently performs) should work just fine. The gridview I have at the moment displays all the images stored in the folder by directly accessing the directory, but I want to be able to display/sort these images based on criteria the user chooses. Storing a reference to the image in the DB allows me to attach a unique identifier in order to facilitate that feature. Thanks a lot for your feedback! – ImNewHere Nov 28 '13 at 04:14
  • Convert image URI to String/Text and save in database. uri.toString() – Mahalakshmi Jan 05 '16 at 05:50

1 Answers1

0

In my application I want to store profile picture of user in SQLite database So I have added one String Column for Storing Path of Image,image will be selected from Gallery

//Executed When user Click on image for selecting profile from Gallery

ImageView profileperson = (ImageView) findViewById(R.id.profileperson);
    profileperson.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 1);
        }
    });

String path;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] fillPath = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, fillPath, null, null, null);
        assert cursor != null;
        cursor.moveToFirst();
        path = cursor.getString(cursor.getColumnIndex(fillPath[0]));
        cursor.close();
        profileperson.setImageBitmap(BitmapFactory.decodeFile(path));
    }
}

Then in for displaying I have fetch path of image using Cursor

String employeeimage;
...
employeeimage = cursor.getString(cursor.getColumnIndex("employeeimage"));  //employeeimage is column name

Now I have display all data in RecyclerView so I have use Adapter for binding data.

List<Data> list = Collections.emptyList();
...
    @Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    /*
    * get items from list of particular position and set into respective textview
    * */

    String path=list.get(position).employeeImage;

    Picasso.with(context).load(new File(path)).into(holder.imageViewPerson);
}
Khyati Vara
  • 1,042
  • 13
  • 22