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

SpeechRecognizer insufficient permissions error with Glass
Access Context from another activty in Android
Actionbar using customview and menuitems
Using just xxhdpi-size icons for Android
How to create ProgressDialog with pause and resume
Unable to export bitmape onto csv
How to add CheckBoxes dynamically to an Android layout? [duplicate]
Adding cast button to ActionBar using the CastCompanionLibrary
OncreateView does not call when Activity get destroyed and re-run again
Error inflating class fragment on Google Maps V2
This code is when checkbox 1+2 of more of the checkbox is checked
popup window instead of popup menu
How to call .NET Web Api from Android App ?
Newbie - Android coding issue of button
Add my application in the share picker list
Decode QR code using Zxing

Categories

HOME
service-worker
kentico
design-patterns
c++11
gpu
pyqt
interface
socket.io
spring-data-mongodb
dojo
big-o
babeljs
google-admin-sdk
jax-ws
flume
character
extjs4.2
qpython
google-schemas
github-enterprise
mod-security
emoji
jsonpath
supervisor
intercom
zerobrane
do-while
internationalization
esoteric-languages
red5
asp.net-mvc-viewmodel
production
jmp
bourbon
sencha-touch
database-connection
resourcebundle
google-api-client
game-theory
windows-server-2003
custom-post-type
jasmine-node
nstimer
android-things
send
kudu
r-grid
android-sugarorm
indy10
browser-extension
searchkit
magento-1.9.2.4
apic
css-position
urlsession
watchface
softmax
naming
subclipse
print-css
mesosphere
cnc
geotiff
remedy
android-testing
css-transforms
choice
cronexpression
atlas
webjars
envi
myspace
turbo-prolog
inf
custom-errors
qt5.2
include-guards
binomial-theorem
rpart
slash
omnifaces
git-ftp
kubuntu
diff3
j-security-check
broadband
exceldatareader
mruby
genymotion-call
paw
mintty
malformedurlexception
android-framework
koala
ecslidingviewcontroller
bin
gpars
asdf
octal
video-codecs
idn
patricia-trie
nokia-s40
sentestingkit
faye
mapping-by-code
flex-mobile
saxparseexception
umra
facebook-iframe
message-passing
scrollbars
lobo-cobra
localizable.strings
flvplayback
wspbuilder

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