如何使用onClicklistener从Gridview获取SQLite数据库row_ID?

时间:2014-06-04 11:54:36

标签: android sqlite android-sqlite android-gridview sqliteopenhelper

首先,我能够将存储在SQLite数据库中的图像路径加载到Gridview中,但我似乎无法找到一种基于SQLite数据库获取图像路径位置的方法带有onClicklistener的Gridview中的row_ID用于删除目的。

我试过这个:

//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;

    }
};

但无论SQLite数据库的row_ID如何,它总是从0开始给我一个位置。

我的目标是根据SQLite数据库中的row_ID,使用onClicklistener从Gridview获取图像路径的位置。

例如,

SQLite数据库:

ROW_ID:
3

4

5

当我点击Gridview中的图片时,

它会给我从3而不是0开始的row_id。

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;

    }
}       
}

如果有人可以帮助我,我们将不胜感激。

非常感谢。

编辑:添加

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();
}

1 个答案:

答案 0 :(得分:1)

您应该将适配器传递给模型对象的arraylist;称之为myArray。使用具有对所需路径的引用的模型对象填充数组。然后你可以调用myArray.get(position),它会给你一个模型对象;称之为myObject。然后调用myObject.getPath()。

模型对象:您创建的具有要检索的密切相关数据的类(请参阅http://www.javapractices.com/topic/TopicAction.do?Id=187),在这种情况下,它将引用图片位置。您应该为每个字段输入模型类setter和getter。您的类将有一个字段,其中包含对图像路径的引用。

类似的东西:

class MyPic {
    private String path;

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

     }

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

}