获取视图的ID在GridView控件 [英] Get ID of View in GridView

查看:146
本文介绍了获取视图的ID在GridView控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经试过


您好,大家好,我首先创建我已经装满3 Collumns数据库,的的RowID,imageID,文字。的后来,我创建了一个GridView这要是在填写我的数据库。现在,我已经创建了一个onItemClickListner,其中我想克服的位置imageID。
在那之后我happend我的检索算法DB-表这imageID后,得到的文本的。这东西我nneed我在其他表进行保存。
问题是我想,我没有得到imageID,而像这样的检索算法在DB没什么,如果你看看在你logcat中看到,它是空,所以它可能没拿到imageID还是我在我DBAdapter搜索不喜欢我应该的。


IMPORTRANT:
我终于得到了THX查看到FuzzialLogic的ID,但仍然是一个问题,我不能让排在我的光标。请看看这个!

<-----------------------------------------------------WORKS---------------------------------------------------------------->
我需要做什么在我的code改变,我可以得到图像的用户点击的ID。后来我想搜索我的数据库与图像的ID,让我随图像存储的文本。
这东西之后去我在其他表。

到这里看到code和LogCat中,日志。
如果有人需要它,我也加了我DatabaseAdapter。
THX对您的帮助提前!

code


SFilterConfigActivity.class:

 包de.retowaelchli.filterit;进口的java.util.ArrayList;进口android.app.Activity;
进口android.content.Intent;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.EditText;
进口android.widget.GridView;
进口android.widget.Toast;
进口的Andr​​oid *。进口de.retowaelchli.filterit.database.SmileyDBAdapter;
进口de.retowaelchli.filterit.database.SFilterDBAdapter;
进口de.retowaelchli.filterit.stats.ImageAdapter;
公共类SFilterConfigActivity延伸活动{    // Variablen deklarieren
    私人字符串名称;
    私人字符串关键字;
    私人字符串笑脸;
    私人字符串文本;    私人字符串来源;
    私人整数[]信息;    私人SmileyDBAdapter SmileyHelper;
    私人SFilterDBAdapter mDbHelper;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.sfilter_config);      SmileyHelper =新SmileyDBAdapter(本);
      mDbHelper =新SFilterDBAdapter(本);      getImages();
      格();
    }
公共无效网格(){    //海尔wird死的GridView definiert UND anschliesend尤伯杯巢穴ImageAdaptergefüllt
    最终的GridView的GridView =(GridView控件)findViewById(R.id.SmileyGrind);
    gridview.setAdapter(新ImageAdapter(这一点,资讯));
    //海尔wird在德的GridView geklickt wird definiert被passiert德恩AUF EIN画报
    gridview.setOnItemClickListener(新OnItemClickListener(){        公共无效onItemClick(适配器视图&LT;&GT;母公司,视图V,INT位置,长的id){
            Toast.makeText(SFilterConfigActivity.this,+位置,Toast.LENGTH_SHORT).show();
           // gridview.setSelection(位置);
           // Funktioniert NOCH NICH自定义的GridView布局dafürERSTELLEN世赫#1
            如果(位置== gridview.getSelectedItemPosition()){
                v.setBackgroundColor(0xFF00FF00);            }
            其他{
                v.setBackgroundColor(0x0000000);
            }            //海尔wird herrausgefunden welche ID DAS画报帽子书房jeweiligen字符串gespeichert UND
            。来源=(新龙(ID))的toString();            SmileyHelper.open();
            光标C = SmileyHelper.getSmiley(源);
            startManagingCursor(C);            如果(c.moveToFirst()){
                做{
                文字= c.getString(c.getColumnIndex(SmileyDBAdapter.SOURCE));
                笑脸= c.getString(c.getColumnIndex(SmileyDBAdapter.INFO));                }而(c.moveToNext());
            SmileyHelper.close();
            }        }    });
}
公共整数[] getImages(){    SmileyHelper.open();    光标C = SmileyHelper.getAllSmileys();    ArrayList的&LT;整数GT; infoList =新的ArrayList&LT;整数GT;();    c.getColumnIndex(SmileyDBAdapter.INFO);
    INT参数:columnIndex = c.getColumnIndex(SmileyDBAdapter.INFO);    如果(C!= NULL)
    {       而(c.moveToNext()){
           字符串infoItem = c.getString(参数:columnIndex);
           infoList.add(的Integer.parseInt(infoItem));
       }
    }
    信息= infoList.toArray(新的整数[] {});    c.close();
    SmileyHelper.close();
    返回信息;}公共无效onClickSConfigSave(视图v){    的EditText edtTextName =(EditText上)findViewById(R.id.SFConfigName);
    的EditText edtTextKeyword =(EditText上)findViewById(R.id.SFConfigKeyword);    。名称= edtTextName.getText()的toString();
    。关键字= edtTextKeyword.getText()的toString();    mDbHelper.open();
    mDbHelper.createSFilter(姓名,关键词,笑脸,文字);
    mDbHelper.close();    最终意图I =新意图(这一点,SmileyActivity.class);
    startActivity(ⅰ);
    }
}

ImageAdapter.class

 包de.retowaelchli.filterit.stats;进口android.content.Context;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.BaseAdapter;
进口android.widget.GridView;
进口android.widget.ImageView;
//进口de.retowaelchli.filterit.SFilterConfigActivity;公共类ImageAdapter延伸BaseAdapter {    //我们的图像的引用
    私人整数[] mThumbIds;
    私人语境mContext;
    公共ImageAdapter(上下文C,整数[] imageIds){
        mContext = C;
        mThumbIds = imageIds;    }    公众诠释的getCount(){
       返回mThumbIds.length;
    }    公共对象的getItem(INT位置){
        返回mThumbIds [位置]
    }    众长getItemId(INT位置){
        返回的位置;
    }    //创建由适配器引用的每个项目的新的ImageView
    公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
        ImageView的ImageView的;
        如果(convertView == NULL){//如果它没有回收,初始化一些属性
            ImageView的=新ImageView的(mContext);
            imageView.setLayoutParams(新GridView.LayoutParams(85,85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8,8,8,8);
        }其他{
            ImageView的=(ImageView的)convertView;
        }        imageView.setId(mThumbIds [位置]);        imageView.setImageResource(mThumbIds [位置]);
        返回ImageView的;
    }}

喜欢我添加的照片与一些文本的DB:

 私人无效愤怒(){        INT drawableID = context.getResources()则getIdentifier(愤怒,绘制,getPackageName());
        iv.setImageResource(drawableID);        //字符串信息=将String.valueOf(drawableID);
        字符串信息=将String.valueOf(drawableID);        mDbHelper.open();        mDbHelper.createSmiley(你收到了愤怒的消息,信息);        mDbHelper.close();
    }

日志 - 猫


和这里的日志:

  11月10日至十二日:32:29.632:DEBUG /数据库(25130):dbopen():PATH = /data/data/de.retowaelchli.filterit/databases/filterit,旗= 6
11月10日至12日:32:29.632:DEBUG /数据库(25130):dbopen():PATH = /data/data/de.retowaelchli.filterit/databases/filterit,免费大小= 663
11月10日至12日:32:30.612:DEBUG /数据库(25130):dbopen():PATH = /data/data/de.retowaelchli.filterit/databases/filterit,标志= 6
11月10日至12日:32:30.612:DEBUG /数据库(25130):dbopen():PATH = /data/data/de.retowaelchli.filterit/databases/filterit,免费大小= 663
11月10日至12日:32:30.632:ERROR /数据库(25130):错误插入文本= NULL笑脸= NULL关键字=测试名称=测试
11月10日至12日:32:30.632:ERROR /数据库(25130):android.database.sqlite.SQLiteConstraintException:错误code 19:约束失败
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.database.sqlite.SQLiteStatement.native_execute(本机方法)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1671)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1515)
11月10日至12日:32:30.632:ERROR /数据库(25130):在de.retowaelchli.filterit.database.SFilterDBAdapter.createSFilter(SFilterDBAdapter.java:89)
11月10日至12日:32:30.632:ERROR /数据库(25130):在de.retowaelchli.filterit.SFilterConfigActivity.onClickSConfigSave(SFilterConfigActivity.java:143)
11月10日至12日:32:30.632:ERROR /数据库(25130):在java.lang.reflect.Method.invokeNative(本机方法)
11月10日至12日:32:30.632:ERROR /数据库(25130):在java.lang.reflect.Method.invoke(Method.java:507)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.view.View $ 1.onClick(View.java:2186)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.view.View.performClick(View.java:2532)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.view.View $ PerformClick.run(View.java:9277)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.os.Handler.handleCallback(Handler.java:587)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.os.Handler.dispatchMessage(Handler.java:92)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.os.Looper.loop(Looper.java:143)
11月10日至12日:32:30.632:ERROR /数据库(25130):在android.app.ActivityThread.main(ActivityThread.java:4196)
11月10日至12日:32:30.632:ERROR /数据库(25130):在java.lang.reflect.Method.invokeNative(本机方法)
11月10日至12日:32:30.632:ERROR /数据库(25130):在java.lang.reflect.Method.invoke(Method.java:507)
11月10日至12日:32:30.632:ERROR /数据库(25130):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)
11月10日至12日:32:30.632:ERROR /数据库(25130):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11月10日至12日:32:30.632:ERROR /数据库(25130):在dalvik.system.NativeStart.main(本机方法)


在这里,你找我SmileyDBAdapter的code。

SmileyDB

 包de.retowaelchli.filterit.database;进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;公共类SmileyDBAdapter {        公共静态最后弦乐ROW_ID =_id;
        公共静态最后弦乐SOURCE =源;
        公共静态最后弦乐信息=信息;        私有静态最后弦乐DATABASE_TABLE =笑脸;        私人DatabaseHelper mDbHelper;
        私人SQLiteDatabase MDB;        私人最终上下文mCtx;        私有静态类DatabaseHelper扩展SQLiteOpenHelper {            DatabaseHelper(上下文的背景下){
                超(背景下,DBAdapter.DATABASE_NAME,空,DBAdapter.DATABASE_VERSION);
            }            @覆盖
            公共无效的onCreate(SQLiteDatabase DB){
            }            @覆盖
            公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
            }
        }        / **
         *构造函数 - 需要上下文允许数据库是
         *打开/创建
         *
         * @参数CTX
         *在其中工作的上下文
         * /
        公共SmileyDBAdapter(上下文CTX){
            this.mCtx = CTX;
        }
        公共SmileyDBAdapter的open()抛出的SQLException {
            this.mDbHelper =新DatabaseHelper(this.mCtx);
            this.mDb = this.mDbHelper.getWritableDatabase();
            返回此;
        }        / **
         *密切的返回类型:无效
         * /
        公共无效的close(){
            this.mDbHelper.close();
        }
        众长createSmiley(源字符串,字符串信息){
            ContentValues​​ initialValues​​ =新ContentValues​​();
            initialValues​​.put(SOURCE,源);
            initialValues​​.put(INFO,资讯);
            返回this.mDb.insert(DATABASE_TABLE,空,initialValues​​);
        }
        公共布尔deleteSmiley(长ROWID){            返回this.mDb.delete(DATABASE_TABLE,ROW_ID +=+ ROWID,NULL)&GT; 0;
        }        公共光标getAllSmileys(){            返回this.mDb.query(DATABASE_TABLE,新的String [] {ROW_ID,
                    SOURCE,INFO},NULL,NULL,NULL,NULL,NULL);
        }
        //居wird NACH德宫ID笑脸gesucht。
        公共光标getSmiley(字符串信息)抛出的SQLException {            光标mCursor =            this.mDb.query(真,DATABASE_TABLE,新的String [] {ROW_ID,来源,
                    信息},INFO +=+信息,NULL,NULL,NULL,NULL,NULL);
            如果(mCursor!= NULL){
                mCursor.moveToFirst();
            }
            返回mCursor;
        }
        公共布尔updateSmiley(长ROWID,源字符串,字符串信息,
                字符串缓存){
            ContentValues​​ ARGS =新ContentValues​​();
            args.put(SOURCE,源);
            args.put(INFO,资讯);            返回this.mDb.update(DATABASE_TABLE,ARGS,ROW_ID +=+ ROWID,NULL)大于0;
        }    }

DBAdapter

 包de.retowaelchli.filterit.database;进口android.content.Context;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;公共类DBAdapter {    公共静态最后弦乐DATABASE_NAME =filterit;    公共静态最终诠释DATABASE_VERSION = 1;    公共静态最后弦乐CREATE_TABLE_ADFILTER =创建表adfilter(_id整数主键自动增量
    + ADFilterDBAdapter.NAME +不为空,
    + ADFilterDBAdapter.KEYWORD +不为空,
    + ADFilterDBAdapter.CACHE +NOT NULL);;    私有静态最后弦乐CREATE_TABLE_SFILTER =创建表sfilter(_id整数主键自动增量
    + SFilterDBAdapter.NAME +不为空,
    + SFilterDBAdapter.KEYWORD +不为空,
    + SFilterDBAdapter.SMILEY +不为空,
    + SFilterDBAdapter.TEXT +NOT NULL);;    私有静态最后弦乐CREATE_TABLE_ADMESSAGES =创建表admessages(_id整数主键自动增量
    + MessagesDBAdapter.PHONENUMBER +不为空,
    + MessagesDBAdapter.MESSAGE +NOT NULL);;
    私有静态最后弦乐CREATE_TABLE_SMILEY =创建表的笑脸(_id整数主键自动增量
    + SmileyDBAdapter.SOURCE +不为空,
    + SmileyDBAdapter.INFO +NOT NULL);;
    私人最终上下文的背景下;
    私人DatabaseHelper DBHelper;
    私人SQLiteDatabase分贝;    / **
     *构造
     * @参数CTX
     * /
    公共DBAdapter(上下文CTX)
    {
        this.context = CTX;    }    私有静态类DatabaseHelper扩展SQLiteOpenHelper
    {
        DatabaseHelper(上下文的背景下)
        {
            超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
        }        @覆盖
        公共无效的onCreate(SQLiteDatabase DB)
        {
            db.execSQL(CREATE_TABLE_ADFILTER);
            db.execSQL(CREATE_TABLE_SFILTER);
            db.execSQL(CREATE_TABLE_ADMESSAGES);
            db.execSQL(CREATE_TABLE_SMILEY);
        }        @覆盖
        公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,
        INT静态网页)
        {
            //添加任何表MODS的这个家伙在这里
        }
    }   / **
     *打开分贝
     返回:此
     * @throws的SQLException
     *返回类型:DBAdapter
     * /
    公共DBAdapter的open()抛出的SQLException
    {
        this.DBHelper =新DatabaseHelper(this.context);
        this.db = this.DBHelper.getWritableDatabase();
        返回此;
    }    / **
     *关闭分贝
     *返回类型:无效
     * /
    公共无效的close()
    {
        this.DBHelper.close();
    }}



解决方案

Safari浏览器,

寻找你的code和分析这可能是导致该错误后,我注意到一些事情。问题是,你的code试图互换ROWID和viewID,但实际上不是所需的行为。

OnItemClick() ID 参数指的是 ROWID 。其实你不具有 ROWID 这是保证(由code)是唯一的,所以它是失败的。虽然你可以强迫问题通过 getItemId(),该功能只提供一个指向对象(整数)。忽略 getItemId(),因为这只是给你造成的痛苦。相反,抢视图本身,而 viewId 直接从它那里得到,像这样:

修改 源= v.getId()的toString();
原因:的自表不声明类型,它是最有可能会作为一个字符串。我们知道ImageID现在回来了,我们知道数据是存在的。所以留下的类型转换,到目前为止,我可以告诉。

视图常引起混淆,尤其是令人费解的嵌套布局像 GridView的列表视图。然而,你的 GridView控件很简单, v 应参照的ImageView 存储在那里。如果的ImageView 储存在的LinearLayout 或其它类似的家长,有可能是一个问题,但不是这种案例你。

这将绕过你需要担心的 getItemId(INT位置),因为再次,这是指 ROWID 如果你能保证到适配器某些事情,只能特别是一个独特的 ROWID 为每个项目。

二,你的 viewId 设置为一个整数,而不是值本身的指针。一个 INT 是一个原始的,所以分配情况如预期。一个整数对象这样的分配发生了对象的地址,而不是对象本身。我建议改变 imageView.setId(mThumbIds [位置]); (在 getView())为:

  imageView.setId(mThumbIds [位置] .intValue());

这将得到原始的 INT 值,而不是在内存中的整数对象的引用。除非别的大侠在您的code发生(我没有看到任何副手的权利),这应该解决您的问题。 SETID 意味着,如果不适当的 ID 分配给它静静地失败,所以它可能无法正常工作,只是不告诉你的。

最后,我不能看到什么类型的字段源是在你的code。它不显示实际的表的创建。因此,在您的特定数据库进一步猜测是不可能的。希望这有助于!

关于你的数据库
脱颖而出有关数据库的主要事情是你的CREATE TABLE语句为您Simleys表。在SQLite的,如果你没有明确指定类型的SQLite将确定类型每次进行查询时,并返回根据它认为什么是该领域的类型。这意味着,数字可能会间preTED为String,反之亦然。在一般情况下,它可以是pretty可靠,但是,它可能会导致缺陷。

一个在code中的最大问题是假设code是做你想让它是什么。事实上,你可以,如果你告诉它到底是什么做的唯一保证这一点。

第二,我注意到,当你建立你的阵列 ImageAdapter ,你正在做的图像字段中的信息查询,而不是 SOURCE 。这是在code作为你告诉误导 onItemClick ,你所得到的 SOURCE 。考虑改变这个变量名。

接下来,查询信息通过 字段getSmiley(字符串信息)时,有一个功能障碍。它期待一个字符串,而不是根据你的论点的整数。添加字符串 ContentValues​​ 对象要比添加一个Integer不同。 A 字符串与'周围,分离'1'从1。这意味着所有的整数被添加插入为字符串,当你查询你不包括必要的'。因此建议了一些变化。


  • 首先,调整你的CREATE TABLE语句。

    私有静态最后弦乐CREATE_TABLE_SMILEY =创建表的笑脸(_id整数主键自动增量
    + SmileyDBAdapter.SOURCE +不为空,
    + SmileyDBAdapter.INFO +整数NULL);


以这种方式更改该语句将确保你得到一个整数,而不是字符串。


  • 接下来,按以下方式更改 getImages()字符串infoItem = c.getString(参数:columnIndex); INT infoItem = c.getInt(参数:columnIndex);


  • 接下来,修改你的 createSmiley(字符串源字符串信息) createSmiley(字符串源,诠释资讯)。这应正确调整所有的刀片。你的 ContentValues​​ 对象(名为 initialValues​​ )会知道该怎么做。


  • 接下来,修改你的 getSmiley(字符串信息) getSmiley(INT资讯)。这应该调整你的查询正确的为好。如果没有,更改 ... +=+信息+ ... ... +=+ info.toString ()+ ... 。这将迫使问题给你。


  • 接下来,修改这一行源= v.getId()的toString()让你的 onItemClick()匹配; 源= v.getId();


  • 最后,你将不得不更改任何您的通话以 createSmiley()发送int值,而不是转换为字符串值。


这是一个很大的变化(不是真的)进行。所以,请备份您的源文件,这些更改之前。然后,它只是一个问题卸载包(包括仿真器,如果是仿真)和重新安装它,所以它不保留原始数据(用字符串,而不是整数)的。

FuzzicalLogic

What I've tried


Hello Guys, I first created a database which I've filled with 3 Collumns, RowID, imageID, text. Afterwards I created a GridView which if filled over my database. Now I have created a onItemClickListner, in which I'd like to get the imageID over the position. After that happend I serach my DB-Table after this imageID, to get the text. This stuff I nneed to save in my other Table. The problem is I think, that I don't get the imageID, and like this serach for nothin in the DB, if you take a look at the Logcat you see that it's null, so it probably didn't get the imageID or I search in my DBAdapter not like I should.

Question


IMPORTRANT: I finally get the ID of the View thx to FuzzialLogic, but there is still a problem, I can't get Row over my Cursor. Please take a look at that!

<-----------------------------------------------------WORKS----------------------------------------------------------------> What do I need to change in my Code, that I can get the ID of the Image the User clicked on. Afterwards I'd like to search my DB with that Image-ID, to get the Text which I stored with the Image. This stuff afterwards goes in my other Table.

Down here you see the Code and LogCat-Log. I also added my DatabaseAdapter if someone needs it. Thx for your help in Advance!

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's 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;




    }

}

Like this I added the pictures with some text to the DB:

   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


And here's the Log:

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)


Here you find the Code of my 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();
    }

}


解决方案

Safari,

After looking over your code and analyzing what could be causing the error, I've noticed a few things. The issue is that your code is trying to interchange the rowID and viewID, but that is not actually the desired behavior.

In OnItemClick(), the id argument refers to rowID. You don't actually have a rowID that is guaranteed (by the code) to be unique, so it is failing. While you could "force the issue" via getItemId(), that function merely provides a pointer to an object (Integer). Ignore getItemId() as this is only causing you pain. Instead, grab the view itself, and get the viewId directly from it, like so:

EDIT source = v.getId().toString(); Reason: Since your TABLE doesn't declare a Type, it is most likely going in as a String. We know the ImageID is now returning, and we know the data is there... So that leaves type conversion, so far as I can tell.

parent and view often cause confusion, particularly with convoluted nested layouts like GridViews and ListViews. However, your GridView is quite simple and v should refer to the ImageView that is stored there. If the ImageView was stored in a LinearLayout or other similar parent, there might be an issue, but such is not the case for you.

This will bypass your need to worry about the getItemId(int position), as again, this refers to rowId and only works if you can guarantee to the Adapter certain things, specifically a unique rowId for each item.

Second, your viewId is set to a pointer for an Integer and not the value itself. An int is a primitive, so assignment happens as expected. An Integer is an Object so assignment happens to the address of the object, not the object itself. I would suggest changing imageView.setId(mThumbIds[position]); (in your getView()) to:

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

This will get the primitive int value instead of a reference to an Integer object in memory. Unless something else errant is happening in your code (and I don't see anything right offhand), this should resolve your issue. setId is meant to fail quietly if an inappropriate id is assigned to it, so it may not be working and simply not telling you.

Finally, I can't see what type of field the 'SOURCE' is in your code. It doesn't show the actual table creation. So, further guessing at your particular database is impossible. Hope this helps!

Regarding your Database The main thing that stands out about your Database is your CREATE TABLE statement for your Simleys Table. In SQLite, if you do not explicitly assign a Type, SQLite will determine the Type each time you make a query, and return the type according to what it believes is in the field. This means that numbers may be interpreted as String and vice versa. In general, it can be pretty reliable, however, it can lead to pitfalls.

One of the biggest issues in code is assuming the code is doing what you want it to. In fact, you can only guarantee this if you tell it exactly what to do.

Second, I noticed that when you get the images to build your Array for your ImageAdapter that you are doing a query on the INFO field, not the SOURCE. This is misleading in your code as you tell the onItemClick that you are getting the SOURCE. Consider changing this variable name.

Next, there is a dysfunction when querying the INFO field via getSmiley(String info). It is expecting a String and not an Integer according to your arguments. Adding a String to a ContentValues object is different than adding an Integer. A String gets added with '' surrounding it, separating '1' from 1. This means that all of your Integers were INSERTED as String and when you are querying you are not including the necessary ''. So a number of changes is advised.

  • First, adjust your CREATE TABLE Statement.

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

Changing the statement in this way will ensure that you are getting an integer and not a string.

  • Next, change your getImages() in the following manner: String infoItem = c.getString( ColumnIndex ); to int infoItem = c.getInt( ColumnIndex );

  • Next, change your createSmiley(String source, String info) to createSmiley(String source, int info) . This should adjust all of your inserts correctly. Your ContentValues object (named initialValues) will know what to do.

  • Next, change your getSmiley(String info) to getSmiley(int info). This should adjust your query correctly as well. If it does not, change ... + "=" + info + ... to ... + "=" + info.toString() + .... This will force the issue for you.

  • Next, make your onItemClick() match by changing this line source = v.getId().toString(); back to source = v.getId();

  • Finally, you will have to change any of your calls to createSmiley() to send the int value, not the value converted to a String.

This is a lot of changes (not really) to make. So, please back up your source files before you make these changes. Then its just a matter of uninstalling the package (including from the emulator, if it is emulated) and reinstalling it, so it doesn't keep the original data (with the Strings and not the Integers).

FuzzicalLogic

这篇关于获取视图的ID在GridView控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆