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

Music Player in android
How to draw a path on an Android canvas with animation?
Change button background for a short period of time
Sms logs - Content resolver
Alarm clock application in iphone and android using phonegap
Getting list/array of dates for a selected month and year in android
I try to download a google file, there isn't errors but it doesn't work
Selecting a contact and retrieveing phone number
Sum query in sqlite in android
getting null in URL in OAuthRequestTokenTask in Twitter in Android?
select from database where id = value from spinner
App force close on debug, logcat is a bully
Resizing a bitmap that automatically rotates
Opencv Android Eclipse speed worse on tutorial1 than tutorial 2 why ?????/
Show a Custom Image When No AdMob Ad Is Available
Custom row elements in ListFragment are displaying incorrectly after scrolling

Categories

HOME
google-cloud-platform
github-for-windows
datastore
interface
camera
graphics
sublimetext
aws-cli
tail
telegram-bot
hugo
polling
android-json
crystal-reports-2013
frontend
extjs4.2
tput
radgridview
keytool
event-sourcing
feathersjs
dreamweaver
vuejs
digital-signature
sse
tiki-wiki
licensing
carrierwave
google-cast
mockjax
jett
android-maps-extensions
jwplayer6
openalpr
google-earth-engine
projects-and-solutions
vmware-fusion
branching-and-merging
claims
linter
arules
er-diagram
d3-force-directed
trigger.io
cd-burning
vcloud-director-rest-api
simplepie
uicolor
greatest-n-per-group
xdoclet
dbamp
phpwebsocket
jparsec
jaunt-api
crouton-os
themoviedb-api
oracle-spatial
microsoft-reporting
google-books
sapscript
amiga
branch-and-bound
jsvc
google-refine
entity-framework-4.3
android-broadcast
apache-spark-1.3
iso-prolog
angular-carousel
lambda-architecture
cancellation
matrix-inverse
tinyxml
radiant
windows-embedded-standard
light
gpars
pagedown
tree-balancing
panda3d
boost-msm
web-farm
faye
lambdaj
jdb
screen-size
htdocs
android-holo-everywhere
lr
codebase
feasibility
scrubyt

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