Question

First of all, I am able to load the image paths that are stored in SQLite Database into the Gridview, but I can't seem to find a way to get the position of the image path based on the SQLite Database row_ID from the Gridview with onClicklistener for deleting purposes.

I've tried this:

//CHECKBOXES ONCLICKLISTENER    
AdapterView.OnItemClickListener Checkbox_MulClickListener = new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        adapter.changeSelection(v, position);

        System.out.println("position : " + position);

        return;

    }
};

But it always gives me the position started from 0 regardless of the SQLite Database row_ID.

My goal is to get the position of the image path from the Gridview with onClicklistener based on the row_ID's in the SQLite Database.

For example,

SQLite Database:

row_id:
3

4

5

when I click on the image from the Gridview,

it would give me the row_id started from 3 instead of 0.

SQLite_Database.java:

public class SQLite_Database extends SQLiteOpenHelper {

private static final String KEY_ID = "ROW_ID";
private static final String KEY_IMAGE = "image_file";
private static final String DATABASE_NAME = "imagesdb";
private static final int DATABASE_VERSION = 1;
private static final String IMAGES_TABLE_NAME = "images";
private static final String IMAGES_TABLE_CREATE =
        "CREATE TABLE " + IMAGES_TABLE_NAME + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE + " TEXT);";

ViewSwitcher viewSwitcher;                                                  
Gallery_Adapter_Activity adapter;

public SQLite_Database(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(IMAGES_TABLE_CREATE);
    db.execSQL(COUNT_TABLE_CREATE);
}

public void addImageFile(String file) {
    ContentValues values = new ContentValues();
    values.put(KEY_IMAGE, file);                    
    getWritableDatabase().insert(IMAGES_TABLE_NAME, null, values);

}



public ArrayList<SDcardPath_Activity> readImageFiles() {                        //(0)     //(1)   
    Cursor cursor = getReadableDatabase().query(IMAGES_TABLE_NAME, new String[] { KEY_ID, KEY_IMAGE }, null, 
                                                                                        null, null, null, null);                                                            
    try {
        if (!cursor.moveToFirst()) {
            SQLiteDatabase db = this.getWritableDatabase();         
            db.delete(IMAGES_TABLE_NAME, null, null);       
            db.close();
        }


        ArrayList<SDcardPath_Activity> sdcardPath_SQLite_Path = new ArrayList<SDcardPath_Activity>();

        do {
            String SQ_single_key_id = cursor.getString(0);      
            String SQ_single_path   = cursor.getString(1);  

            Shared_Data_Class shared_data_class = new Shared_Data_Class();                  SDcardPath_Activity SQ_SDcardPath_Class = new SDcardPath_Activity();

            shared_data_class.putID(Integer.parseInt(SQ_single_key_id));

            SQ_SDcardPath_Class.sdcardPath = SQ_single_path;
            sdcardPath_SQLite_Path.add(SQ_SDcardPath_Class);

        } while (cursor.moveToNext());
        return sdcardPath_SQLite_Path;

    }
    finally {
        cursor.close();
    }
  }


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    // on upgrade drop older tables
    db.execSQL("DROP TABLE IF EXISTS " + IMAGES_TABLE_CREATE);

    // create new tables
    onCreate(db);

}


// Deleting single SQLite_data
public void delete_SQLite_data(Shared_Data_Class shared_data_class) {
    SQLiteDatabase db = this.getWritableDatabase();

    db.delete(IMAGES_TABLE_NAME, KEY_ID + " = ?", new String[] { 
    String.valueOf(shared_data_class.read_String_method()) });      

    db.close();                                                                             
}


 }

Image_MainActivity.java:

  public class Image_MainActivity extends Activity {

ArrayList<Shared_Data_Class> Shared_Data_Class_DATA = new ArrayList<Shared_Data_Class>();


GridView gridGallery;
Handler handler;
Gallery_Adapter_Activity adapter;

Button add_images_btn;

ViewSwitcher viewSwitcher;
ImageLoader imageLoader;

   SQLite_Database SQ_LITE_DATABASE;

int add_image_count;
int result_requestcode = 542182;
public boolean isSeleted;
public String sdcardPath;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    initImageLoader();
    init();

  //Initialize other classes (or else error will occur)
    SQ_LITE_DATABASE = new SQLite_Database(Image_MainActivity.this);

 //LOAD IMAGE PATHS FROM SQLITE_DATABASE TO THE GRIDVIEW  
 try {
     ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();        
    viewSwitcher.setDisplayedChild(0);
    adapter.addAll(SQLite_Databse_Data);

 } catch (Exception e) 
 {
    e.printStackTrace();
    return;
 }  

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

        @Override
        public void onClick(View v) {               


            }
        });
    }

private void initImageLoader() {
    @SuppressWarnings("deprecation")
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheOnDisc().imageScaleType
    (ImageScaleType.EXACTLY_STRETCHED).bitmapConfig(Bitmap.Config.RGB_565).build();

    ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
            this).defaultDisplayImageOptions(defaultOptions).memoryCache(new WeakMemoryCache());

    ImageLoaderConfiguration config = builder.build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);
}



   //CHECKBOXES ONCLICKLISTENER 
AdapterView.OnItemClickListener Checkbox_MulClickListener = new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        adapter.changeSelection(v, position);

        System.out.println("position : " + position);

        return;

    }
};





private void init() {

    handler = new Handler();
    gridGallery = (GridView) findViewById(R.id.main_gridGallery);
    gridGallery.setFastScrollEnabled(true);                     //To have fast scroll bar on the screen
    adapter = new Gallery_Adapter_Activity(getApplicationContext(), imageLoader);
    gridGallery.setOnItemClickListener(Checkbox_MulClickListener);      //for checkboxes OnItemClickListener
    adapter.setMultiplePick(true);      //Turn on checkboxes in Image_MainActivity Class
    gridGallery.setAdapter(adapter);

    viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
    viewSwitcher.setDisplayedChild(1);


    Button done_button = (Button) findViewById(R.id.done);      
    done_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {       //Done Button OnClickListener

            finish();

        }                       
    });

    add_images_btn = (Button) findViewById(R.id.add_images_button);
    add_images_btn.setOnClickListener(new View.OnClickListener() {                              

        @Override
        public void onClick(View v) {       //Add Images Button OnClickListener

            Intent i = new Intent(Multiple_Pick_Activity.ACTION_MULTIPLE_PICK);
            startActivityForResult(i, result_requestcode);          
                                    //result_requestcode is the sent code. The request code must match
        }

    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

                     //result_requestcode is the sent code. The request code must match
    if (requestCode == result_requestcode && resultCode == Activity.RESULT_OK)
                                                                  //RESULT_OK is from Gallery_View_Activity
        {       

        SDcardPath_Activity SDcardPath_Class = new SDcardPath_Activity();

        String[] ALL_Paths = data.getStringArrayExtra("all_path");

        for (String single_path : ALL_Paths) 
        {      

            SQ_LITE_DATABASE.addImageFile(single_path);           // Add single_path to method addImageFile() {
                                                                  // in SQLite_Database class                                                   
        }

  try { 


        ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();
        SQLite_Databse_Data.add(SDcardPath_Class);

        viewSwitcher.setDisplayedChild(0);
        adapter.addAll(SQLite_Databse_Data);        

        Intent intent = new Intent (Image_MainActivity.this, Image_MainActivity.class);
        startActivity(intent);
        finish();

       } catch (Exception e) 
       {
        e.printStackTrace();
        return;

    }
}       
}

If someone can help me, it would be greatly appreciated.

Thank you very much.

edit: added

Gallery_Adapter_Activity.java

@Override
public int getCount() {
    return data.size();
}

@Override
public SDcardPath_Activity getItem(int position) {
    return data.get(position);
}

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

public void setMultiplePick(boolean isMultiplePick) {
    this.isActionMultiplePick = isMultiplePick;
}

public void selectAll(boolean selection) {
    for (int i = 0; i < data.size(); i++) {
        data.get(i).isSeleted = selection;

    }
    notifyDataSetChanged();
}
Was it helpful?

Solution

You should pass into your adapter an arraylist of model objects; call it myArray. Populate the array with model objects that have a reference to the path you want. Then you can call myArray.get(position), that will give you a model object; call it myObject. Then call myObject.getPath().

Model Object: a class you create that has closely related data you want to retrieve (see http://www.javapractices.com/topic/TopicAction.do?Id=187), in this case it will have a reference to a picture location. You should put in your model class setters and getters for each field. Your class will have a field that holds a reference to the path to your image.

Something like:

class MyPic {
    private String path;

     public MyPic(String path){
         this.path = path;

     }

     public getPath(){
         return path;
     }
     etc . . . 

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top