2012-03-21 2 views
0

내 앱으로 진행했지만 버튼의 이미지 뷰 (이 예제에서는 상태)를 검색하기 위해 구현해야하는 것이 무엇인지 알아 내려고 노력했습니다. 내 사용자 지정 어댑터 sqlite 테이블에서 모든 행에 대한 항목을 유지합니다 (_id에 의해) 책갈피되었습니다.북마크 된 항목에 대한 사용자 지정 어댑터를 통해 상태를 SQLite 테이블에 저장합니다.

아래와 같이 setSelected()를 사용하여 이미지 뷰를 변경할 수있는 사용자 정의 SimpleCursorAdapter가 지금 북마크 된 항목을 식별하고 테이블에 저장하는 메커니즘을 만들어야하는 경우. 나는 또한 ... 그것을 구현하는 방법을 잘 내가하는 일에 구상 것에 만

public class DxSimpleCursorAdapter extends SimpleCursorAdapter { 
Context context; 
Activity activity; 
    private DxDbAdapter mDbHelper; 

public DxSimpleCursorAdapter(Context context, int layout, Cursor c, 
     String[] from, int[] to) { 
    super(context, layout, c, from, to); 
    this.context=context; 
    this.activity=(Activity) context; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent){ 
    View row = super.getView(position, convertView, parent); 

    ImageView image = (ImageView) row.findViewById(R.id.fav); 

    //Query for _id of row item and see if there is an entry for it on the favourite table 
    //Then change ImageView to being selected image (yellow star) 
    //Else leave default image (greyed out) 


    image.setOnClickListener(new View.OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      ImageView fav = (ImageView) v.findViewById(R.id.fav); 
      fav.setImageResource(R.drawable.ic_fav); 

      long rowID = (Long) v.getTag(); 
      Toast toast = Toast.makeText(context, "" + rowID, Toast.LENGTH_SHORT); 
      toast.show(); 

      mDbHelper = new DxDbAdapter(context); 
      int result = mDbHelper.isFav(rowID); 

      if (result == 0) { 
       v.setSelected(true); 
      } 
      else { 
       v.setSelected(false); 
      } 
     } 
    }); 
    return row; 
} 
} 

을 // 주석을 넣어 가지고, 내가 좋아하는 추가 할 수 있도록 기능을 만드는 오전 내 데이터베이스에 대한 어댑터가 항목을 테이블에 있지만 사용자 지정 커서 어댑터에서 DB를 호출 할 수 있는지 또는 다른 방식으로 처리해야하는지 여부를 알 수 없습니다. 다음과 같이

public class DxDbAdapter { 

public static final String DIAG_ID = "_id"; 
public static final String DIAG_CAT = "category"; 
public static final String DIAG_SUB = "subcategory"; 
public static final String DIAG = "diagnosis"; 
public static final String DIAG_CODE = "diagcode"; 
public static final String FAV_CODE = "edid"; 

private static final String DATABASE_NAME = "dx"; 
private DatabaseHelper mDbHelper; 
private SQLiteDatabase mDb; 

protected static Context mCtx; 

private static class DatabaseHelper extends SQLiteOpenHelper { 

    public DatabaseHelper (Context context) { 
     super(context, DATABASE_NAME, null, 1); 
     } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
      String s; 
      try { 
        Toast.makeText(mCtx, "1", 2000).show(); 
        InputStream in = mCtx.getResources().openRawResource(R.raw.sql); 
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
        Document doc = builder.parse(in, null); 
        NodeList statements = doc.getElementsByTagName("statement"); 
        for (int i=0; i<statements.getLength(); i++) { 
          s = statements.item(i).getChildNodes().item(0).getNodeValue(); 
          db.execSQL(s); 
        } 
      } catch (Throwable t) { 
        Toast.makeText(mCtx, t.toString(), 50000).show(); 
      } 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      db.execSQL("DROP TABLE IF EXISTS DiagLookups"); 
      onCreate(db); 
    } 
} 

public DxDbAdapter(Context context) { 
    this.mCtx = context; 
} 

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

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

public Cursor fetch(int level, String param) { 
    Cursor cursor = null; 
    switch (level) { 
    case 0: 
     cursor = mDb.rawQuery("Select distinct _id, diagnosis, diagcode, favourite From DiagLookup Where category = ? order by diagnosis asc", new String[]{""+param}); 
     break; 
    case 1: 
     cursor = mDb.rawQuery("Select distinct _id, diagnosis, diagcode, favourite From DiagLookup Where subcategory = ? order by diagnosis asc", new String[]{""+param}); 
     break; 
    } 
    return cursor; 
} 

public Cursor fetchFavs() { 
    Cursor cursor = mDb.rawQuery("Select distinct _id, diagnosis, diagcode, favourite From DiagLookup Where favourite = 1 order by diagnosis asc", null); 
    return cursor; 
} 

public int isFav(Long param) {  
    Cursor cursor = mDb.rawQuery("Select favourite From DiagLookup Where _id = ?", new String[]{""+param}); 
    int result = cursor.getInt(cursor.getColumnIndex(FAV)); 
    return result; 
} 

내 테이블 구조는 다음과 같습니다

CREATE TABLE IF NOT EXISTS Lookup (
_id INTEGER PRIMARY KEY, 
category VARCHAR(150), 
subcategory VARCHAR(150), 
diagnosis VARCHAR(150), 
diagcode VARCHAR(150), 
favourite INTEGER) 

내가 DB를 오픈()을 만들 listactivity 있습니다. 거기에서 데이터를 커서로 가져 와서 내 DxSimpleCursorAdapter에 전달합니다.

모든 안내가 크게 감사하겠습니다. 커서에 액세스 할 수 있도록

감사

답변

1

당신은 bindView()newView() 방법을 구현해야합니다.

class ViewHolder { 
    ImageView image; 
    // other views that you have in your row layout 
} 
: 우리는 전체 레이아웃 우리가 행 뷰를 액세스 할 때마다 검색하지 않도록 견해를 개최한다 어댑터의 클래스가

@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     LayoutInflater inflater = LayoutInflater.from(context); // you should put this in the constructor so you don't do it every time the newView() method is called 
     View row = inflater.inflate(R.layout.row_layout, null); 
     // even implement the view holder pattern for a small performance boost 
     ViewHolder holder = new ViewHolder(); 
     holder.image = (ImageView) row.findViewById(R.id.the_id_of_the_image); 
     row.setTag(holder); 
     return row; 
} 

ViewHolder입니다 : newView()에서는 레이아웃을 팽창

그러자 bindView() 구현 방법 : newView에서

@Override 
public void bindView(View v, Context con, Cursor cursor) { 
     ViewHolder holder = (ViewHolder) v.getTag() //retrieve the holder with the row views 
     // set the current image status 
     int status = cursor.getInt(cursor.getColumnIndex(FAV_CODE)); // get the status(I don't know how you store the favorite status, I assumed is an int in the FAV_CODE column, 1 for favorite, 0 for unpicked yet) 
     if (status == 1) { 
      // the user set as favorite 
      holder.image.setImageResource(R.drawable.favorite); // set the favorite drawable 
     } else { 
     // this isn't a favorite so put the default image 
     holder.image.setImageResource(R.drawable.normal); // set the normal drawable 
     } 
     //get the row id from the cursor that we will pass in the onClick method as a tag for the image 
     long id = cursor.getLong(cursor.getColumnIndex(DIAG_ID)); 
     holder.image.setTag(new Long(id)); 
     // set the image listener 
     holder.image.setOnClickListener(new View.OnClickListener(){ 

     @Override 
     public void onClick(View v){ 
      long rowID = (Long) v.getTag(); 
      //there is no need to find the view, and you don't modify the imageview image from here  
      // query the database to find the row with the _id equal to rowID 
      // find out what value we have in the column with the image status (either 1 or 0 meaning favorite or not favorite) 
      // update the row with the new status (if you have 1 in the database then update the status with 0 , if you have 0 in the database then update the value with 1) 
      //call notifyDatasetChanged on the adapter to let the adapter know about the update, I don't know if this call will work with SimpleCursorAdapter, you may have to set a new adapter on the ListView with a new cursor. 
     } 
     }); 

} 
+0

() 코드 holder.image = (이미지 뷰) findViewById를 (R.id.the_id_of_the_image)를; android.view.View를 가져 왔지만 findViewByID가 DxSimpleCursorAdapter에 대해 정의되지 않았다고 말하기 때문에 작동하지 않습니다. 다음을 사용하려고했습니다. \t \t row.setTag (holder.image.findViewById (R.id.fav)); 어떤 오류가 발생하지 않았지만 응용 프로그램을 에뮬레이션 할 때 강제 종료 오류가 발생하여 NullPointerException이 발생했습니다. – DeucePie

+0

@DeucePie 죄송합니다. 팽창 된 행 레이아웃에서 해당 ID를 검색해야합니다. 내 작은 편집을 참조하십시오. – Luksprog

+0

bindView()를 사용하여 getView()를 사용하는 것과 내 접근 방식을 사용하는 것의 차이점은 무엇입니까? – DeucePie

관련 문제