0

I am wondering how to get the imagePath of the image stored in the drawable folder in eclipse. The imagePath is to be stored in SQLite Database. So now I am wondering how do I retrieve the Uri of the imagePath in the database. Any help will be greatly appreciated. Thank you.

ImagePage.java

package main.page;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class ImagesPage extends Activity 
{
    Integer[] imageIDs = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4};
    ImageAdapter imgDB = new ImageAdapter(this);

    ArrayList<String> imageNames = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image);

        Button btnNext = (Button)findViewById(R.id.buttonNext);
        btnNext.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
            Intent i = new Intent(ImagesPage.this, ImagesSecondpage.class);
            startActivity(i);

            }
        });


        GridView gridView = (GridView)findViewById(R.id.gridview);
        gridView.setAdapter(new ImgAdapter(this));      

        gridView.setOnItemClickListener(new OnItemClickListener()
        {

                @Override
                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id)
                {
                    imgDB.open();
                    long _id = imgDB.insertImage("pic" + (position + 1)+ ".jpg");

                    imgDB.close();
                }
        }); 
    }

    public class ImgAdapter extends BaseAdapter
      {
          private Context context;

          public ImgAdapter(Context c)
          {
              context = c;

          }


        @Override
        public int getCount()
        {
        return imageIDs.length;
        }

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

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

        @Override
        public View getView(int position, View convertView ,ViewGroup parent)
        {
          ImageView imageView;
          if(convertView == null)
          {
              imageView = new ImageView(context);
              imageView.setImageResource(getResources().getIdentifier(imageNames.get(position), defType, defPackage))
              imageView.setLayoutParams(new GridView.LayoutParams(85,85));
              imageView.setScaleType(ImageView.ScaleType.FIT_XY);
              imageView.setPadding(5, 5, 5, 5);

          }else
          {
              imageView = (ImageView) convertView;
          }
            imageView.setImageResource(imageIDs[position]);
            return imageView;


        }

     }

}

ImageAdapter.java

    package main.page;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ImageAdapter
{
    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "img_name";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "anniversary";
    private static final String DATABASE_TABLE = "image";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE = "create table image (_id integer primary key autoincrement, "+ "img_name text not null);";
    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public ImageAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

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

        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
          try
          {
            db.execSQL(DATABASE_CREATE);
          }catch(SQLException e)
          {
              e.printStackTrace();
          }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version" +oldVersion + "to" + newVersion +", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS image");
            onCreate(db);   
        }



    }


    public ImageAdapter open() throws SQLException
    {
        db = DBHelper.getReadableDatabase();
        return this;
    }

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

    public long insertImage(String img_name)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, img_name);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    public boolean deleteImage(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID +"="+ rowId, null) > 0;
    }

    public Cursor getAllImages()
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null, null, null, null);
    }

    public Cursor getImage(long rowId) throws SQLException
    {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, KEY_ROWID +"="+ rowId, null, null, null, null, null);
        if(mCursor != null)
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateImage(long rowId, String img_name)
    {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, img_name);
        return db.update(DATABASE_TABLE, args, KEY_ROWID +"="+ rowId, null) > 0;
    }

}

I have updated the coding for the ImagePage.java again.

CallMyName
  • 84
  • 1
  • 2
  • 11
  • See this [link](http://stackoverflow.com/questions/11595665/saving-resources-path-in-sqlite) Let me know if it works for you. njoy!! – moDev Jul 27 '12 at 09:12
  • Hi, thanks for the link but I don't understand how the answer works. I suppose the image refers to the imageView? Then the resId variable I don't get it. – CallMyName Jul 30 '12 at 01:24

2 Answers2

1
String path = getResources().getString(R.drawable.icon);
MAC
  • 15,799
  • 8
  • 54
  • 95
  • What if I want to do the reverse? That is pass a string `"R.drawable.icon"` and get the int that represents the image? – CodyBugstein Oct 10 '14 at 13:29
0

any image resource should be placed in drawable so its not about path you just need the image name to be saved in database related to some entity and the by getting it from database you can get the image resource through the code below

Bitmap image = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier( "imagename" , "drawable", getPackageName()));

Update:

as now from your code according to question you were trying to get images through name(path) means instead of Integer array Integer[] imageIDs = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3, R.drawable.pic4}; you want image resources to be pointed through database so to do this first you have to get all image names(the names same as the name of images in drawable folder) you saved in column of a table in database once you got the names through query then instead of reference through Integer array just the names from database will allow you to access the image resources from drawables, im supposing that image names are stored by following way ArrayList<String> imageNames = new ArrayList<String>(); //hence in the while loop of cursor during retriving values from cursor imageNames.add(cursor.getString(columnIndex));

so the updated code will like below where

@Override
        public View getView(int position, View convertView ,ViewGroup parent)
        {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(getResources().getIdentifier(imageNames.get(position), "drawable", this.getPackageName()));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
            imageView.setBackgroundResource(itemBackground);


            return imageView;
        }

if you still confused then there is no other solution i think i can do

Umar Qureshi
  • 5,985
  • 2
  • 30
  • 40
  • Hi, thanks for answering my answer. But I don't quite get what you mean by relate the image name to some entity. Could you explain further because I am still a beginner android programmer. Thanks. – CallMyName Jul 30 '12 at 01:38
  • entity is not android specific terminology i just mean here that when you save any row of data in which you want to save image reference also for that entry. like you have users table containing different fields i.e username, password, first name,...., Image. for each entry in image column instead of full path you just need to save image name in android because all the image resources always to be placed in drawable folder so path is confirmed you just get image names from database against each row and put it in above line of code by replacing "imagename" and you will able to get that image. – Umar Qureshi Jul 30 '12 at 08:15
  • Hi, I understand the part on inserting the image's name into the database and if I replaced the image name with the line of codes that you have typed above it will work, I suppose that's what you are trying to say? – CallMyName Jul 30 '12 at 08:53
  • you will not replace image name with line of code but when you want to get image through its name as you saved name in database then in your code you have to put the above code line which is in my answer and where i written "imagename" you have to put the name of image(which you most probably getting from database through code) there. – Umar Qureshi Jul 30 '12 at 09:38
  • Hi, I have uploaded my codes to my answer above. If possible, could you help me to see which part of the codes could be improved? Thanks a lot. – CallMyName Jul 31 '12 at 01:29
  • Hi I have edited my codes again but I haven't implement your codes into my own. Could you help me check to see where I can improve on? Sorry for all the trouble and I really thanks you for your help. Greatly appreciated it. – CallMyName Aug 01 '12 at 04:11