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

android - how to check bluetooth baudrate in adb shell
How to prevent launcher activity to appear in android multitask section?
ActionBarPullToRefresh Progress Bar
Handling multiple views in android
Captcha Dialog Layout (Android)
Different APK for MDPI, HDPI, XHDPI and XXHDPI
Passing values from android activity to custom view
Nothing showing on screen with custom listview adapter
android.view.InflateException: Binary XML file line #13: Error inflating class fragment
How to move action bar icons to overflow icons automatically?
Animation when pressing “back” button on android fragment
Android Custom ContentProvider fails on Image Preview
GPS Proximity Alert Doesn't Work
XMLHttpRequest - empty responseText but status 200 and readyState 4
Fragments disappears after adding ButtonBar to the layout
expand background of action bar menuItem to height of actionbar

Categories

HOME
android
beautifulsoup
angular2-material
swt
socket.io
grafana
newrelic
dojo
ado.net
google-cloud-datalab
retrofit2
vert.x
pkcs#11
syntaxnet
symmetricds
chargify
enterprise-miner
monit
beta
dapper-extensions
linked-data
8051
genexus-sd
datastax-enterprise-graph
tizen-tv
vex
testcomplete
postback
paragraph
record
android-sugarorm
biztalk-rule-engine
nested-lists
html-encode
alphabetical
zoomify
android-augmented-reality
apache-stanbol
resolution
vmware-fusion
android-softkeyboard
escpos
parser-generator
movilizer
glm-math
lpsolve
jquery-ui-draggable
fclose
dtsearch
trojan
static-cast
wpas
colorbar
check-mk
reshape
java-websocket
swingworker
redbeard-ios
flex4.6
signalr.client
windows-azure-queues
scaffolding
installshield-2010
google-query-language
createprocess
database-relations
findfirst
np-spring
toast
toran-proxy
decimalformat
pypiserver
flock
iced-coffeescript
dronekit-android
diff3
ssis-data-flow
spy++
machine-instruction
genymotion-call
gtm-oauth2
breakout
jeromq
dtmf
rolify
pstack
monotouch.dialog
dajaxice
adobe-media-server
cross-database
google-ajax-api
metaweblog
non-clustered-index
rowlex
wordprocessingml
asynchronous-wcf-call

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