0

anyone can help me.

i have listview item from database when i add an imagebutton.

here is my view image button..

<ImageButton
                android:id="@+id/heart"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:src="@drawable/heart"
                android:layout_gravity="right|top"
                android:background="#ffffff" />

and in my adapter i have OnClickListener event..

buttonHeart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (arg0 != null) {
                    FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
                    database.open();

                    if(favorite.matches("0")) {
                        database.updateItemFavorite(_id,"1");
                        buttonHeart.setImageResource(R.drawable.heartred);
                    }else if(favorite.matches("1")){
                        database.updateItemFavorite(_id, "0");
                        buttonHeart.setImageResource(R.drawable.heart);
                    }
                }
            }
        });

in my OnClickListener i check if(favorite.matches("0")) then i setImageResource(R.drawable.heartred);

else if(favorite.matches("1")) then i setImageResource(R.drawable.heart);

this thing is worked.

if the button is heart when i clicked it, it change to heartred

but the problem is when i scroll the listview, the heartred turn again to heart.

please help me.

here is the complete adapter..

public class FragmentOne_Adapter extends CursorAdapter {

    public FragmentOne_Adapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void bindView(View view, final Context context, final Cursor cursor) {
        // TODO Auto-generated method stub
        TextView txtTitle = (TextView) view.findViewById(R.id.title);
        TextView txtArtist = (TextView) view.findViewById(R.id.artist);
        TextView txtVolume = (TextView) view.findViewById(R.id.volume);
        TextView txtNumber = (TextView) view.findViewById(R.id.number);

        final ImageButton buttonHeart = (ImageButton) view.findViewById(R.id.heart);


        final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
        String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
        String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
        final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
        String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));

        // Populate fields with extracted properties
        txtTitle.setText(title);
        txtArtist.setText(artist);
        txtVolume.setText(volume);
        txtNumber.setText(number);

        if(favorite.matches("0")) {
            buttonHeart.setImageResource(R.drawable.heart);
        }else if(favorite.matches("1")){
            buttonHeart.setImageResource(R.drawable.heartred);
        }

        buttonHeart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (arg0 != null) {
                    FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
                    database.open();

                    if(favorite.matches("0")) {
                        database.updateItemFavorite(_id,"1");
                        buttonHeart.setImageResource(R.drawable.heartred);
                    }else if(favorite.matches("1")){
                        database.updateItemFavorite(_id, "0");
                        buttonHeart.setImageResource(R.drawable.heart);
                    }
                }
            }
        });

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // TODO Auto-generated method stub
        return LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
    }

}

here is my fragment..

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_fragment_one, container, false);

        TabHost host = (TabHost) rootView.findViewById(R.id.tabHost);
        host.setup();

        //Tab 1
        TabHost.TabSpec spec = host.newTabSpec("SONG LIST");
        spec.setContent(R.id.tab1);
        spec.setIndicator("SONG LIST");
        host.addTab(spec);


            player1ESearch = (EditText) rootView.findViewById(R.id.player1Search);
            listView = (ListView) rootView.findViewById(R.id.slPlayer1ListView);
            dbHelper = new FragmentOne_DbAdapter(getActivity());
            dbHelper.open();
            //Clean all data
            //dbHelper.deleteAllPlayer1();
            //Add some data
            dbHelper.insertPlayer1Songlist();
            //Generate ListView from SQLite Database
            displayPlayer1ListView();

            ImageButton dplayer1ESearch=(ImageButton) rootView.findViewById(R.id.delete);
            dplayer1ESearch.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        player1ESearch.setText("");
                    }
            });


        //Tab 2
        spec = host.newTabSpec("NEW SONGS");
        spec.setContent(R.id.tab2);
        spec.setIndicator("NEW SONGS");
        host.addTab(spec);

        //Tab 3
        spec = host.newTabSpec("FAVORITES");
        spec.setContent(R.id.tab3);
        spec.setIndicator("FAVORITES");
        host.addTab(spec);

        return rootView;
    }

    private void displayPlayer1ListView() {
        Cursor cursor = dbHelper.fetchAllPlayer1();

        FragmentOneAdapter = new FragmentOne_Adapter(getActivity(), cursor, 0);
        listView.setAdapter(FragmentOneAdapter);

        player1ESearch.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                FragmentOneAdapter.getFilter().filter(s.toString());
            }
        });

        FragmentOneAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                return dbHelper.fetchPlayer1ByTitle(constraint.toString());
            }
        });


    }

and here is my database adapter..

public class FragmentOne_DbAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_ARTIST = "artist";
    public static final String KEY_VOLUME = "volume";
    public static final String KEY_TYPE = "type";
    public static final String KEY_FAVORITE = "favorite";
    public static final String KEY_NUMBER = "number";

    private static final String TAG = "FragmentOne_DbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "Virtualsongbook";
    private static final String SQLITE_TABLE = "Player1";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static final String DATABASE_CREATE =
            "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                    KEY_ROWID + " integer PRIMARY KEY autoincrement," +
                    KEY_TITLE + "," +
                    KEY_ARTIST + "," +
                    KEY_VOLUME + "," +
                    KEY_TYPE + "," +
                    KEY_FAVORITE + "," +
                    KEY_NUMBER + ")";

    private static class DatabaseHelper extends SQLiteOpenHelper {

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


        @Override
        public void onCreate(SQLiteDatabase db) {
            //Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public FragmentOne_DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

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

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }

    private boolean isRecordExistInDatabase(String tableName, String field, String value) {
        String query = "SELECT * FROM " + tableName + " WHERE " + field + " = '" + value + "'";
        Cursor c = mDb.rawQuery(query, null);
        if (c.moveToFirst()) {
            c.close();
            return true;
        }
        c.close();
        return false;
    }

    public long createPlayer1(String title,
                              String artist, String volume,
                              String type, String favorite, String number) {

        if(isRecordExistInDatabase(SQLITE_TABLE, KEY_NUMBER, number)){
            return 0;
        }
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_ARTIST, artist);
        initialValues.put(KEY_VOLUME, volume);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_FAVORITE, favorite);
        initialValues.put(KEY_NUMBER, number);

        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }

    public boolean deleteAllPlayer1() {

        int doneDelete = 0;
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        //Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }

    public Cursor fetchPlayer1ByTitle(String titleText) throws SQLException {
        //Log.w(TAG, titleText);
        Cursor mCursor = null;
        if (titleText == null  ||  titleText.length () == 0)  {
            mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                            KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                    null, null, null, null, null);

        }
        else {
            mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
                            KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                    KEY_TITLE + " like '%" + titleText + "%'", null,
                    null, null, null, null);
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    public Cursor fetchAllPlayer1() {

        Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                        KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                null, null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateItemFavorite(long rowId, String favorite) {
        int doneUpdate = 0;
        ContentValues values = new ContentValues();
        values.put(KEY_FAVORITE, favorite);
        doneUpdate =  mDb.update(SQLITE_TABLE, values, KEY_ROWID + "=" + rowId,null);
        return doneUpdate > 0;
    }

    public void insertPlayer1Songlist() {
        //TYPE
        //0 - NONE
        //1 - NEW

        createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 3", "Artist 3", "Vol 3","0","0","12343");
        createPlayer1("Song Title 4", "Artist 4", "Vol 4","0","0","12344");
        createPlayer1("Song Title 5", "Artist 5", "Vol 5","0","0","12345");
        createPlayer1("Song Title 6", "Artist 6", "Vol 6","0","0","12346");
        createPlayer1("Song Title 7", "Artist 7", "Vol 7","0","0","12347");
        createPlayer1("Song Title 8", "Artist 8", "Vol 8","0","0","12348");
        createPlayer1("Song Title 9", "Artist 9", "Vol 9","0","0","12349");
        createPlayer1("Song Title 10", "Artist 10", "Vol 10","0","0","12310");
        createPlayer1("Song Title 11", "Artist 11", "Vol 11","0","0","12311");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","12312");

        createPlayer1("Joemar", "Artist 1", "Vol 1","0","0","09876");
        createPlayer1("Joehamir", "Artist 2", "Vol 2","0","0","76543");
        createPlayer1("Joenair", "Artist 3", "Vol 3","0","0","43211");

    }

}

image of what happening

enter image description here

thanks,

joe

Joe
  • 227
  • 1
  • 4
  • 18
  • In your Adapter's getView method, rebind your data using the same favorite.matches.... logic to reset the imageview. – Abbas Jul 11 '16 at 09:08
  • Which adapter are u using? You should make your own adapter which extends from BaseAdapter... Or are you using RecyclerView? – Abbas Jul 11 '16 at 09:12
  • please see update.. thanks.. sorry im just new to android.. – Joe Jul 11 '16 at 09:14
  • Ok. So I'm confused, there are many different inconsistencies in your code. Why don't you review the code and then try and run the code and then paste a working code sample here. – Abbas Jul 11 '16 at 09:24
  • everything is worked.. my problem is setImageResource, when i click my imagebutton heart it will turn to heartred, but the problem is when i scroll listview it will turn to heart again.. i dont want to turn to heart again because its already heartred.. sorry im not good in english.. – Joe Jul 11 '16 at 09:29
  • Possible duplicate of [ListView reusing views when ... I don't want it to](http://stackoverflow.com/questions/6921462/listview-reusing-views-when-i-dont-want-it-to) – Janki Gadhiya Jul 11 '16 at 09:31

2 Answers2

4

Modify Your Adapter With HolderPattern

public class FragmentOne_Adapter extends CursorAdapter {

        FragmentOne_DbAdapter dbHelper;

        public FragmentOne_Adapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
            // TODO Auto-generated constructor stub
            dbHelper = new FragmentOne_DbAdapter(context);
            dbHelper.open();
        }

        @Override
        public void bindView(View view, final Context context, final Cursor cursor) {
            // TODO Auto-generated method stub
            final ViewHolder holder = (ViewHolder) view.getTag();

            final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
            String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
            String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
            String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
            final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
            String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));

            // Populate fields with extracted properties
            holder.txtTitle.setText(title);
            holder.txtArtist.setText(artist);
            holder.txtVolume.setText(volume);
            holder.txtNumber.setText(number);

            if (favorite.matches("0")) {
                holder.buttonHeart.setImageResource(R.drawable.heart);
            } else {
                if (favorite.matches("1")) {
                    holder.buttonHeart.setImageResource(R.drawable.heartred);
                } else {
                    holder.buttonHeart.setImageResource(R.drawable.heart);
                }
            }

            holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (arg0 != null) {
                        FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
                        database.open();
                        if (favorite.matches("0")) {
                            database.updateItemFavorite(_id, "1");
                            holder.buttonHeart.setImageResource(R.drawable.heartred);
                        } else if (favorite.matches("1")) {
                            database.updateItemFavorite(_id, "0");
                            holder.buttonHeart.setImageResource(R.drawable.heart);
                        }
                    }
                    FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
                }
            });

        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // TODO Auto-generated method stub
//            View rowView = ((LayoutInflater) context
//                    .getSystemService("layout_inflater")).inflate(
//                    R.layout.fragment_fragment_one_slview, parent, false);
            View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
            ViewHolder holder = new ViewHolder();
            holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
            holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
            holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
            holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
            holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);

            rowView.setTag(holder);
            return rowView;
        }


        class ViewHolder {
            TextView txtTitle;
            TextView txtArtist;
            TextView txtVolume;
            TextView txtNumber;
            ImageButton buttonHeart;
        }
    }

See this thread

Community
  • 1
  • 1
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
  • Got the issue what is happening you click and change image and also update the database with new status Cool but the cursor still have the old result so also have update your cursor. – Sohail Zahid Jul 11 '16 at 10:09
  • the data is updated.. when i refresh the fragment thats the time the gray heart will permanently become red.. i want to fix it because it will confuse the user if they tick the heart then when they scroll, it will remove.. – Joe Jul 11 '16 at 10:10
  • replace old adapter with my updated answer i have made some change in adapter. – Sohail Zahid Jul 11 '16 at 10:17
  • hi @Sohail Zahid, can you help me my new problem.. thanks.. http://stackoverflow.com/questions/38321158/android-studio-tabhost-refresh-tab-content – Joe Jul 13 '16 at 07:37
2

Take a look at the viewholder pattern. Listviews reuse their views for performance purposes, this is why you have problems when scrolling. Here is an example: ListView reusing views when ... I don't want it to

Community
  • 1
  • 1
Bram
  • 4,533
  • 6
  • 29
  • 41