jeudi 1 février 2018

Listview with Simple Cursor Adapter checkbox scroll issue?

I have a list view with Simple Cursor Adapter each row in it have a checkbox , textview and an image button. If I check first row's checkbox then on scroll some checkboxes in bottom also got checked. I searched on google and found this is because f recycle of list items but cannot understand any of the answer given so please explain it to me. Following is the view :

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.captcarisma.listapp.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:id="@+id/layout_bottom"
            android:layout_width="match_parent"
            android:layout_height = "50dp"
            android:layout_alignParentBottom = "true"
            android:background="@color/white">
            <EditText
                android:layout_width = "fill_parent"
                android:layout_height = "match_parent"
                android:id="@+id/txt_view"
                android:layout_toStartOf="@+id/tick_btn"
                android:hint="Going To Buy...."
                android:textSize="30sp"
                android:padding="0dp"
                android:background="@null"/>

            <ImageButton
                android:id = "@+id/tick_btn"
                android:layout_toStartOf="@+id/mic_btn"
                android:layout_width = "45dp"
                android:layout_height = "match_parent"
                android:src="@drawable/ic_done_black_24dp"
                android:background="@color/white"
                android:onClick="add_data"
                />
            <ImageButton
                android:id="@+id/mic_btn"
                android:layout_width="45dp"
                android:layout_height="match_parent"
                android:src="@drawable/ic_mic_black_24dp"
                android:background="@color/white"
                android:layout_alignParentEnd="true"
                android:onClick="check"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="fill_parent">

            <ListView
                    android:id="@+id/listView"
                    android:layout_width="match_parent"
                    android:layout_height="fill_parent">
                </ListView>
            </RelativeLayout>
        </LinearLayout>
    </android.support.constraint.ConstraintLayout>
The above is my main activity XML. Following is my single row view XML.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:descendantFocusability="blocksDescendants">
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:id="@+id/pro_check"
        android:translationY="5dp"
        android:onClick="pro_check"/>
    <TextView
        android:textSize="30sp"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_toEndOf="@+id/pro_check"
        android:id="@+id/pro_name"
        />
    <ImageButton
        android:background="@color/white"
        android:id="@+id/del_btn"
        android:layout_width="45dp"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:src="@drawable/ic_delete_forever_black_24dp"
        android:onClick="del_btn"/>
</RelativeLayout>

Here is my activity.java code:

package com.example.captcarisma.listapp;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;

import javax.xml.datatype.Duration;

import static android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS;
public class MainActivity extends AppCompatActivity{
EditText text;
ListView listView;
dataBaseAdapter dataBaseAdapter;
SimpleCursorAdapter simpleCursorAdapter;
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.txt_view);
        dataBaseAdapter = new dataBaseAdapter(this);
        listView = (ListView) findViewById(R.id.listView);
        listView.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);
        populate_list();
    }
    public void populate_list(){
        Cursor cursor = dataBaseAdapter.get_all_data();
        String[] from = new String[]{"item_name"};
        int[] to = new int[]{R.id.pro_name};
        simpleCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.single_row,cursor, from, to,0);
        listView.setAdapter(simpleCursorAdapter);
    }
    public void add_data(View view) {
        if(text.length() != 0){
            long id = dataBaseAdapter.addData(text.getText().toString());
            if (id>=0){
                text.setText("");
                populate_list();
            }else {
                Toast.makeText(this,""+id,Toast.LENGTH_LONG).show();
            }
        }
    }
    public void del_btn(View v){
        int row_id = listView.getPositionForView(v);
        RelativeLayout r = (RelativeLayout) listView.getChildAt(row_id);
        /*CheckBox c = (CheckBox) r.getChildAt(0);
        c.toggle();*/
        long id = simpleCursorAdapter.getItemId(row_id);
        int count = dataBaseAdapter.delete_row(id);
        if(count>0){
            Toast.makeText(this,"Item Deleted.",Toast.LENGTH_LONG).show();
            populate_list();
        }
    }
    public void pro_check(View v){
        boolean checked = ((CheckBox) v).isChecked();
        int row_id = listView.getPositionForView(v);
        RelativeLayout r = (RelativeLayout) listView.getChildAt(listView.getPositionForView(v));
        long id = simpleCursorAdapter.getItemId(row_id);
        TextView t = (TextView) r.getChildAt(1);
        if(checked){
            int counter = dataBaseAdapter.update_status(1,id);
            if(counter > 0){
                t.setPaintFlags(t.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }else {
                Toast.makeText(this,""+counter,Toast.LENGTH_LONG).show();
            }
        }else {
            int counter = dataBaseAdapter.update_status(0,id);
            if(counter > 0){
                t.setPaintFlags(t.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
            }
            else {
                Toast.makeText(this,""+counter,Toast.LENGTH_LONG).show();
            }
        }
    }
    public void check(View view) {
        Intent intent = new  Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        if(intent.resolveActivity(getPackageManager()) != null){
            startActivityForResult(intent,10);
        }else {
            Toast.makeText(this,"This Feature is Not Supported In Your Device.",Toast.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 10:
                if(resultCode == RESULT_OK && data != null){
                    ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    text.setText(result.get(0));
                }
                break;
        }
    }
}

And Here is my databaseadapter class:

package com.example.captcarisma.listapp;
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;
import android.util.Log;
import android.widget.Toast;

import java.io.Console;

import static com.example.captcarisma.listapp.dataBaseAdapter.dataBaseHelper.*;
class dataBaseAdapter {
    dataBaseHelper databasehelper;
    dataBaseAdapter(Context context) {
        databasehelper = new dataBaseHelper(context);
    }
     public long addData(String item){
        SQLiteDatabase sqLiteDatabase = databasehelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(dataBaseHelper.col2,item);
        return sqLiteDatabase.insert(dataBaseHelper.tableName,null,contentValues);
    }
    public Cursor get_all_data(){
        SQLiteDatabase sqLiteDatabase = databasehelper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.query(dataBaseHelper.tableName, new String[]{dataBaseHelper.col1,dataBaseHelper.col2},null,null,null,null,null);
        return cursor;
    }
    public int update_status(int new_value , long id){
        SQLiteDatabase sqLiteDatabase = databasehelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(dataBaseHelper.col3,new_value);
        String[] condition = new String[]{""+id};
        int counter = sqLiteDatabase.update(dataBaseHelper.tableName,contentValues,dataBaseHelper.col1+"=?",condition);
        return counter;
    }
    public int delete_row(long row_id){

        SQLiteDatabase sqLiteDatabase =databasehelper.getWritableDatabase();
        int count = sqLiteDatabase.delete(dataBaseHelper.tableName, dataBaseHelper.col1 + "=?",new String[]{""+row_id});
        return count;
    }
    class dataBaseHelper extends SQLiteOpenHelper{
        private static final String dataBaseName = "list";
        private static final String tableName = "items";
        private static final String col1 = "_id";
        private static final String col2 = "item_name";
        private static final String col3 = "status";
        private static final int dataBaseVersion = 2;
        Context context;
        private static final String qry = "CREATE TABLE "+tableName+"("+col1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+col2+" VARCHAR(255),"+col3+" INTEGER DEFAULT 0);";
        private static final String delete_table = "DROP TABLE IF EXIST "+tableName;
        public dataBaseHelper(Context context) {
            super(context, dataBaseName, null, dataBaseVersion);
            this.context = context;
        }
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            try {
                sqLiteDatabase.execSQL(qry);
                Toast.makeText(context,"DataBase Created.",Toast.LENGTH_LONG).show();
            }catch (SQLException e){
                Toast.makeText(context,""+e,Toast.LENGTH_LONG).show();
            }

        }
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            try {
                Toast.makeText(context,"DataBase Upgraded.",Toast.LENGTH_LONG).show();
                sqLiteDatabase.execSQL(delete_table);
                onCreate(sqLiteDatabase);
            }catch (SQLException e){
                Toast.makeText(context,""+e,Toast.LENGTH_LONG).show();
            }
        }
    }
}

I am new to android so please try to give detailed answer.Thank you!




Aucun commentaire:

Enregistrer un commentaire