android


Listview data keep duplicating


I'm trying to follow this tutorial on how to retain checkbox state in SQLite database. Everything worked fine but the data in the Listview keep duplicating every time I restart the project. How to prevent this from happening?
Screenshot
Adapter:
class CustomCursorAdapter extends CursorAdapter{
private SQLiteDatabase dh=DatabaseHelper.getInstance().getDb();
private LayoutInflater mInflater;
private Context mContext;
private Cursor cursor;
CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(context);
mContext = context;
cursor=c;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// TODO Auto-generated method stub
ViewHolder holder=(ViewHolder)view.getTag();
holder.setTextView((TextView)view.findViewById(R.id.textview));
holder.setCheckBox((CheckBox)view.findViewById(R.id.checkbox));
CheckBox cb=holder.getCheckBox();
holder.getTextView().setText( cursor.getString(cursor.getColumnIndex("username")));
cb.setTag(cursor.getPosition());
CompoundButton.OnCheckedChangeListener checkedChange= new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
ContentValues contentValues=new ContentValues();
Integer currentPosition = (Integer)buttonView.getTag();
String currentPositionString=Double.toString(currentPosition);
if(cursor.moveToPosition(currentPosition))
{
String rowID=cursor.getString(cursor.getColumnIndex("_id"));
if(isChecked){
contentValues.put("selected", "1");
dh.update(DatabaseHelper.USER_PASSWORD, contentValues, "_id=?", new String[]{rowID});
}else {
contentValues.put("selected", "0");
dh.update(DatabaseHelper.USER_PASSWORD, contentValues, "_id=?", new String[]{rowID});
}
}
}
};
cb.setOnCheckedChangeListener(checkedChange);
if(cursor.getString(cursor.getColumnIndex("selected")).compareTo("1")==0)
{
cb.setChecked(true);
}
else
{
cb.setChecked(false);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
View convertView = mInflater.inflate(R.layout.custom, parent,false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
MainActivity.java:
public class MainActivity extends ListActivity{
Cursor cursor;
SQLiteDatabase dh;
CustomCursorAdapter myCursorAdapter;
ContentValues values;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidContext.setContext(this);
dh=DatabaseHelper.getInstance().getDb();
values = new ContentValues();
// Inserting some data in SQLite to populate list view
insertData("Avinash" , "123456");
insertData("Rakesh" , "qwerty");
insertData("Prateek", "onMobile");
insertData("Rajesh", "Symphony");
insertData("Rahul", "password123");
insertData("Kanishk", "_smi1234");
insertData("Ahmad", "asdfgh");
insertData("Akkie", "zxcvbn");
insertData("Ankur", "asdadd");
insertData("Rohit", "bigb");
insertData("Abhi", "rajjwe");
insertData("Sone", "qwerty");
createListView();
}
private void createListView() {
setContentView(R.layout.main);
cursor=dh.query(DatabaseHelper.USER_PASSWORD, new String[]{"_id","username","selected"}, null, null, null, null, "username ASC");
startManagingCursor(cursor);
myCursorAdapter= new CustomCursorAdapter(this,cursor);
this.getListView().setAdapter(myCursorAdapter);
}
private void insertData(String firstName ,String password){
if(values!= null){
values.clear();
}
if (values != null) {
values.put("username", firstName);
}
if (values != null) {
values.put("password", password);
}
dh.insert(DatabaseHelper.USER_PASSWORD, null, values);
}
public void clickHandler(View view){
if(view.getId() == R.id.checkbox){
cursor.requery(); /* to get the updated values from sqlite on changing the check of checkbox*/
}
}
You are inserting new data in the activity's onCreate().
This should happen only once, after the database has been created. The correct place for that is the database open helper's onCreate().
I have an adapter with Image, text and checkbox. Refer this code and fix your error.
Use this adapter:
public class CLVCustomAdapter extends BaseAdapter {
private Context myContext;
private CLVListPojo myList;
private ArrayList<CLVListPojo> myData;
private boolean[] aBoolean;
public CLVCustomAdapter(Context context, ArrayList<CLVListPojo> aData) {
this.myContext = context;
this.myData = aData;
aBoolean = new boolean[aData.size()];
}
#Override
public int getCount() {
if (myData.size() <= 0)
return 1;
return myData.size();
}
#Override
public CLVListPojo getItem(int i) {
return myData.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
/**
* #param position
* #param convertView
* #param parent
* #return
*/
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder aViewHolder;
aViewHolder = new ViewHolder();
LayoutInflater aLayoutInflater = (LayoutInflater) myContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = aLayoutInflater.inflate(R.layout.custom_listview, null);
aViewHolder.aImageView = (ImageView) convertView.findViewById(R.id.custom_listview_IMG);
aViewHolder.aTextView = (TextView) convertView.findViewById(R.id.custom_listview_TXT);
aViewHolder.aCheckBox = (CheckBox) convertView.findViewById(R.id.custom_listview_CHECKBOX);
convertView.setTag(aViewHolder);
if (aBoolean[position]) {
aViewHolder.aCheckBox.setChecked(true);
} else {
aViewHolder.aCheckBox.setChecked(false);
}
aViewHolder.aCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
aBoolean[position] = true;
} else {
aBoolean[position] = false;
}
notifyDataSetChanged();
}
});
myList = getItem(position);
Picasso.with(myContext).load(myList.getUrl()).into(aViewHolder.aImageView);
aViewHolder.aTextView.setText(myList.getUser());
return convertView;
}
public ArrayList<String> getSelectedValues() {
ArrayList<String> aSelecList = new ArrayList<>();
for (int i = 0; i < aBoolean.length; i++) {
if (aBoolean[i]) {
aSelecList.add(getItem(i).getUser());
}
}
return aSelecList;
}
public class ViewHolder {
ImageView aImageView;
TextView aTextView;
CheckBox aCheckBox;
}
}

Related Links

Send data from Thread to Activity / Fragment
Qt + Android: Location of java files common to different projects
Can't perform undo/redo operations in drawing View
How to call database insertion functions in publishProgress function
Pager adapter in baseadapter of listview
Update query failing with transaction enabled sqlite3+android+cocos2dx
Android TV control focus from imageViewA in fragmentA to another imageViewB in fragmentB
Merge Two Sqlite database & dump data from attached database (unable to open database)
SecurityException DownloadManager for android 3.2
Android Can Not Install APK On Phone,SDK Target Issue
Sending data from Intel Galileo to phone
How to know an Android looks whether upwards or downwards? [closed]
installing facebook apk on android emulator via adb endless processing
Can't get objectAnimator working with xFraction
Database sqlite android rewrite
Fragments removed after Activity recreate

Categories

HOME
turing-machines
dns
tivoli
dojo
square
bookmarks
missing-data
boto3
project
little-proxy
minecraft-forge
text-mining
opengl-es-3.0
standards
intershop
google-content-api
identity-management
delphi-xe5
backpack-for-laravel
named-entity-recognition
pimcore
exploit
tiki-wiki
progress-bar
underscore.js
winexe
jaws
gitlab-api
send
hibernate-validator
jett
android-maps-extensions
installshield-le
vue-chartjs
fossil
python-import
pdw-file-browser
protege4
modernizr
nohup
gdata
opensmpp
doc
stringtokenizer
watchface
placeholder
angular-http
optimizely
yii2-api
vugen
lightning
scalding
qtranslate
truezip
payload
type-theory
monkey
baidu
bootstrap-tags-input
rmongo
atlas
seek
tinkerpop3
file-uri
cifilter
firebase-security
spreadjs
ikiwiki
lz77
html-to-pdf
realsense
jparsec
relativelayout
directdraw
state-restoration
sapi
boomerang
decimalformat
dllimport
fiware-monitoring
intel-c++
zen-cart
text-search
canalyzer
rdflib
botan
node-serialport
android-vibration
appserver
ignite-ui
android-framework
fpdi
sbcl
android-audiorecord
away3d
beaker-testing
asdf
font-awesome-4.0.0
mantle
fb.ui
argouml
multiplexing
oracle-enterprise-linux
fitbounds
infobright
node-redis
entitydatasource
uipagecontrol
cac
aspmenu
spread
django-piston
build-environment
dojo-dnd
application-planning
flvplayback
httpcookie

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App