Get View ID in GridView

What i tried


Hi guys, I first created a database that I populated with 3 Collumns, RowID, imageID, text. Subsequently, I created a GridView that was populated over my database. Now I created an onItemClickListner in which I would like to get the imageID above the position. After that, I earned my DB table after that imageID to get the text. I need to save this material in another table. The problem is that I think that I do not get the image identifier, and like this serach for nothin in the DB, if you look at Logcat, you will see that it is null, so it probably did not get the image identifier or I search in my DBAdapter is not as it should.

Question


IMPORTRANT: I finally get the View ID thanks to FuzzialLogic, but there is still a problem, I cannot get Row over my cursor. Please take a look at this!

<--------------------------------------------- ---- ----WORKS----------------------------------------- ---- -------------------> What do I need to change in my code so that I can get the identifier of the image that the user clicked on. Subsequently, I would like to find my database with this Image-ID in order to get the text that I saved with the image. This material is subsequently included in my other table.

Below you see the code and LogCat-Log. I also added my DatabaseAdapter if anyone needs it. Thanks for your help in Advance!

the code


SFilterConfigActivity.class:

    package de.retowaelchli.filterit;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;
import android.*;

import de.retowaelchli.filterit.database.SmileyDBAdapter;
import de.retowaelchli.filterit.database.SFilterDBAdapter;
import de.retowaelchli.filterit.stats.ImageAdapter;




public class SFilterConfigActivity extends Activity {

    //Variablen deklarieren
    private String name;
    private String keyword;
    private String smiley;
    private String text;

    private String source;
    private Integer[] info;

    private SmileyDBAdapter SmileyHelper;
    private SFilterDBAdapter mDbHelper;


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

      SmileyHelper = new SmileyDBAdapter(this);
      mDbHelper = new SFilterDBAdapter(this);

      getImages();
      grid();
    }


public void grid(){

    //Hier wird die GridView definiert und anschliesend über den ImageAdapter gefüllt
    final GridView gridview = (GridView) findViewById(R.id.SmileyGrind);
    gridview.setAdapter(new ImageAdapter(this, info));


    //Hier wird definiert was passiert wenn auf ein Bild in der GridView geklickt wird
    gridview.setOnItemClickListener(new OnItemClickListener(){

        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(SFilterConfigActivity.this, "" + position, Toast.LENGTH_SHORT).show();
           // gridview.setSelection(position);
           // Funktioniert noch nich Custom GridView Layout dafür erstellen siehe Stackoverflow
            if(position == gridview.getSelectedItemPosition()){
                v.setBackgroundColor(0xFF00FF00);

            }
            else{
                v.setBackgroundColor(0x0000000);
            }

            //Hier wird herrausgefunden welche ID das Bild hat und in den jeweiligen String gespeichert
            source = (new Long(id)).toString();

            SmileyHelper.open();
            Cursor c = SmileyHelper.getSmiley(source);
            startManagingCursor(c);

            if (c.moveToFirst()) { 
                do { 
                text = c.getString(c.getColumnIndex(SmileyDBAdapter.SOURCE)); 
                smiley = c.getString(c.getColumnIndex(SmileyDBAdapter.INFO)); 

                } while (c.moveToNext());
            SmileyHelper.close();


            }

        }

    });
}


public Integer[] getImages(){

    SmileyHelper.open();

    Cursor c = SmileyHelper.getAllSmileys();

    ArrayList<Integer> infoList = new ArrayList<Integer>();

    c.getColumnIndex(SmileyDBAdapter.INFO);
    int ColumnIndex = c.getColumnIndex(SmileyDBAdapter.INFO);

    if(c!=null)
    {

       while(c.moveToNext()){
           String infoItem = c.getString( ColumnIndex );
           infoList.add(Integer.parseInt(infoItem));
       }
    }


    info = infoList.toArray(new Integer[]{});

    c.close();


    SmileyHelper.close();


    return info;

}



public void onClickSConfigSave(View v){

    EditText edtTextName = (EditText)findViewById(R.id.SFConfigName);
    EditText edtTextKeyword = (EditText)findViewById(R.id.SFConfigKeyword);

    name = edtTextName.getText().toString();
    keyword = edtTextKeyword.getText().toString();

    mDbHelper.open();
    mDbHelper.createSFilter(name, keyword, smiley, text);
    mDbHelper.close();

    final Intent i = new Intent(this, SmileyActivity.class);
    startActivity(i);
    }
}

ImageAdapter.class

    package de.retowaelchli.filterit.stats;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;


//import de.retowaelchli.filterit.SFilterConfigActivity;

public class ImageAdapter extends BaseAdapter {

    // references to our images
    private Integer[] mThumbIds;
    private Context mContext;


    public ImageAdapter(Context c, Integer[] imageIds) {
        mContext = c;
        mThumbIds = imageIds;

    }



    public int getCount() {
       return mThumbIds.length;
    }

    public Object getItem(int position) {
        return mThumbIds[position];
    }

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

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setId(mThumbIds[position]);

        imageView.setImageResource(mThumbIds[position]);




        return imageView;




    }

}

:

   private void angry(){

        int drawableID = context.getResources().getIdentifier("angry", "drawable", getPackageName());
        iv.setImageResource(drawableID);

        //String info = String.valueOf(drawableID);
        String info = String.valueOf(drawableID);

        mDbHelper.open();

        mDbHelper.createSmiley("You received a angry message", info);

        mDbHelper.close();
    }

Log-Cat


:

10-12 11:32:29.632: DEBUG/Database(25130): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, flag = 6
10-12 11:32:29.632: DEBUG/Database(25130): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, free size = 663
10-12 11:32:30.612: DEBUG/Database(25130): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, flag = 6
10-12 11:32:30.612: DEBUG/Database(25130): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, free size = 663
10-12 11:32:30.632: ERROR/Database(25130): Error inserting text=null smiley=null keyword=test name=test
10-12 11:32:30.632: ERROR/Database(25130): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
10-12 11:32:30.632: ERROR/Database(25130):     at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
10-12 11:32:30.632: ERROR/Database(25130):     at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
10-12 11:32:30.632: ERROR/Database(25130):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1671)
10-12 11:32:30.632: ERROR/Database(25130):     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1515)
10-12 11:32:30.632: ERROR/Database(25130):     at de.retowaelchli.filterit.database.SFilterDBAdapter.createSFilter(SFilterDBAdapter.java:89)
10-12 11:32:30.632: ERROR/Database(25130):     at de.retowaelchli.filterit.SFilterConfigActivity.onClickSConfigSave(SFilterConfigActivity.java:143)
10-12 11:32:30.632: ERROR/Database(25130):     at java.lang.reflect.Method.invokeNative(Native Method)
10-12 11:32:30.632: ERROR/Database(25130):     at java.lang.reflect.Method.invoke(Method.java:507)
10-12 11:32:30.632: ERROR/Database(25130):     at android.view.View$1.onClick(View.java:2186)
10-12 11:32:30.632: ERROR/Database(25130):     at android.view.View.performClick(View.java:2532)
10-12 11:32:30.632: ERROR/Database(25130):     at android.view.View$PerformClick.run(View.java:9277)
10-12 11:32:30.632: ERROR/Database(25130):     at android.os.Handler.handleCallback(Handler.java:587)
10-12 11:32:30.632: ERROR/Database(25130):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-12 11:32:30.632: ERROR/Database(25130):     at android.os.Looper.loop(Looper.java:143)
10-12 11:32:30.632: ERROR/Database(25130):     at android.app.ActivityThread.main(ActivityThread.java:4196)
10-12 11:32:30.632: ERROR/Database(25130):     at java.lang.reflect.Method.invokeNative(Native Method)
10-12 11:32:30.632: ERROR/Database(25130):     at java.lang.reflect.Method.invoke(Method.java:507)
10-12 11:32:30.632: ERROR/Database(25130):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-12 11:32:30.632: ERROR/Database(25130):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-12 11:32:30.632: ERROR/Database(25130):     at dalvik.system.NativeStart.main(Native Method)

SmileyDBAdapter.

SmileyDB

package de.retowaelchli.filterit.database;

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;

public class SmileyDBAdapter {

        public static final String ROW_ID = "_id";
        public static final String SOURCE = "source";
        public static final String INFO = "info";

        private static final String DATABASE_TABLE = "smiley";

        private DatabaseHelper mDbHelper;
        private SQLiteDatabase mDb;

        private final Context mCtx;

        private static class DatabaseHelper extends SQLiteOpenHelper {

            DatabaseHelper(Context context) {
                super(context, DBAdapter.DATABASE_NAME, null, DBAdapter.DATABASE_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }
        }

        /**
         * Constructor - takes the context to allow the database to be
         * opened/created
         * 
         * @param ctx
         *            the Context within which to work
         */
        public SmileyDBAdapter(Context ctx) {
            this.mCtx = ctx;
        }


        public SmileyDBAdapter open() throws SQLException {
            this.mDbHelper = new DatabaseHelper(this.mCtx);
            this.mDb = this.mDbHelper.getWritableDatabase();
            return this;
        }

        /**
         * close return type: void
         */
        public void close() {
            this.mDbHelper.close();
        }


        public long createSmiley(String source, String info ){
            ContentValues initialValues = new ContentValues();
            initialValues.put(SOURCE, source);
            initialValues.put(INFO, info);
            return this.mDb.insert(DATABASE_TABLE, null, initialValues);
        }


        public boolean deleteSmiley(long rowId) {

            return this.mDb.delete(DATABASE_TABLE, ROW_ID + "=" + rowId, null) > 0;
        }

        public Cursor getAllSmileys() {

            return this.mDb.query(DATABASE_TABLE, new String[] { ROW_ID,
                    SOURCE, INFO }, null, null, null, null, null);
        }




        //Es wird nach der ID des smiley gesucht.
        public Cursor getSmiley(String info) throws SQLException {

            Cursor mCursor =

            this.mDb.query(true, DATABASE_TABLE, new String[] { ROW_ID, SOURCE,
                    INFO }, INFO + "=" + info, null, null, null, null, null);
            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }


        public boolean updateSmiley(long rowId, String source, String info,
                String cache){
            ContentValues args = new ContentValues();
            args.put(SOURCE, source);
            args.put(INFO, info);

            return this.mDb.update(DATABASE_TABLE, args, ROW_ID + "=" + rowId, null) >0; 
        }

    }

DBAdapter

package de.retowaelchli.filterit.database;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {

    public static final String DATABASE_NAME = "filterit";

    public static final int DATABASE_VERSION = 1;

    public static final String CREATE_TABLE_ADFILTER = "create table adfilter (_id integer primary key autoincrement, "
    + ADFilterDBAdapter.NAME+" not null ,"
    + ADFilterDBAdapter.KEYWORD+" not null ,"
    + ADFilterDBAdapter.CACHE + " not null );";

    private static final String CREATE_TABLE_SFILTER = "create table sfilter (_id integer primary key autoincrement, "
    +SFilterDBAdapter.NAME+" not null ,"
    +SFilterDBAdapter.KEYWORD+" not null ,"
    +SFilterDBAdapter.SMILEY+ " not null ,"
    +SFilterDBAdapter.TEXT+ " not null );";

    private static final String CREATE_TABLE_ADMESSAGES = "create table admessages (_id integer primary key autoincrement, "
    +MessagesDBAdapter.PHONENUMBER+" not null ,"
    +MessagesDBAdapter.MESSAGE+ " not null );";


    private static final String CREATE_TABLE_SMILEY = " create table smiley (_id integer primary key autoincrement, "
    +SmileyDBAdapter.SOURCE+" not null ,"
    +SmileyDBAdapter.INFO+ " not null );";


    private final Context context; 
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    /**
     * Constructor
     * @param ctx
     */
    public DBAdapter(Context ctx)
    {
        this.context = ctx;

    }

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

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            db.execSQL(CREATE_TABLE_ADFILTER);
            db.execSQL(CREATE_TABLE_SFILTER);
            db.execSQL(CREATE_TABLE_ADMESSAGES);
            db.execSQL(CREATE_TABLE_SMILEY);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, 
        int newVersion) 
        {               
            // Adding any table mods to this guy here
        }
    } 

   /**
     * open the db
     * @return this
     * @throws SQLException
     * return type: DBAdapter
     */
    public DBAdapter open() throws SQLException 
    {
        this.DBHelper = new DatabaseHelper(this.context);
        this.db = this.DBHelper.getWritableDatabase();
        return this;
    }

    /**
     * close the db 
     * return type: void
     */
    public void close() 
    {
        this.DBHelper.close();
    }

}

+5
4

,

, , . , rowID viewID, .

OnItemClick() id rowID. rowID, ( ), , . " " getItemId(), (Integer). getItemId(), . viewId :

source = v.getId().toString(); . TABLE , . , ImageID , , ... , , .

parent view , GridViews ListViews. GridView v ImageView, . ImageView LinearLayout , , .

getItemId(int position), -, rowID , Adapter , rowID .

-, viewId Integer, . int , , . Integer - Object, , . imageView.setId(mThumbIds[position]); ( getView()) :

   imageView.setId(mThumbIds[position].intValue());

int Integer . - ( ), . setId , id, .

, , "SOURCE" . . , . , !

, , - CREATE TABLE Simleys. SQLite, , SQLite , , , , , . , String . , , .

, , . , , , .

-, , Array ImageAdapter, INFO, SOURCE. , onItemClick, SOURCE. .

, INFO getSmiley(String info) . , . String ContentValues . A String "", "1" 1. , Integers String, , "". .

  • CREATE TABLE.

    private static final String CREATE_TABLE_SMILEY = " (_include ," + SmileyDBAdapter.SOURCE + "not null", + SmileyDBAdapter.INFO + "integer not null);";

, , .

  • getImages() : String infoItem = c.getString( ColumnIndex ); int infoItem = c.getInt( ColumnIndex );

  • createSmiley(String source, String info) createSmiley(String source, int info). . ContentValues ( initialValues) , .

  • getSmiley(String info) getSmiley(int info). . , ... + "=" + info + ... ... + "=" + info.toString() + .... .

  • OnItemClick() , source = v.getId().toString(); source = v.getId();

  • , createSmiley(), int, , String.

( ). . ( , ) , ( , ).

FuzzicalLogic

+2

ImageAdapter. getItemid ther, 0, . mThumbIds [position] , .

.

+2

ImageAdapter getView

imageView.setId(mThumbIds[postion]);

Onclick gridview click

source = (new Long(id)).toString();

source = parent.getItemId(position);

.

+1
source

change

  if(c!=null)
    {

       while(c.moveToNext()){
           String infoItem = c.getString( ColumnIndex );
           infoList.add(Integer.parseInt(infoItem));
       }
    }

to

if(c!=null)
        {

           while(!c.isAfterLast()){
               String infoItem = c.getString( ColumnIndex );
               infoList.add(Integer.parseInt(infoItem));
               c.moveToNext();
           }
        }
0
source

All Articles