Unchecking Checkboxes in Custom Listview - android

I want to unchecked my all check boxes inside listview on button click.
This my adapter class. It unchecked all check boxes but for that I have to scroll through listview.
When I scroll through it, it unchecked according to the rows that are visible.
public class ExpenseCalculatorAdapter extends ArrayAdapter<String>{
private Activity context;
private static LayoutInflater inflator = null;
private ArrayList<String> data;
private ArrayList<String> values;
DataBaseUtil dbUtils;
public ExpenseCalculatorAdapter(Activity context, ArrayList<String> data){
super(context,R.layout.expenserow, data);
this.context = context;
this.data = data;
dbUtils=new DataBaseUtil(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String row=data.get(position);
String date;
String type;
String cost;
final String id;
/* result.add(c.getString(iRowid)+"&"+c.getString(iDate)+"~"+c.getString(iCost)+"#"+c.getString(iType)+"*");*/
id=row.substring(0, row.indexOf("&"));
date=row.substring(row.indexOf("&")+1,row.indexOf("~"));
cost=row.substring(row.indexOf("~")+1,row.indexOf("#"));
type=row.substring(row.indexOf("#")+1,row.indexOf("*"));
if(convertView==null)
{
ViewHolder holder = new ViewHolder();
inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.expenserow, null);
holder.togCheck=(CheckBox)convertView.findViewById(R.id.check);
holder.textDate = (TextView) convertView.findViewById(R.id.txtrowDate);
holder.textType = (TextView) convertView.findViewById(R.id.txtrowType);
holder.textCost = (TextView) convertView.findViewById(R.id.txtrowCost);
holder.togCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setAction("clicked");
if(buttonView.isChecked())
{
try
{
dbUtils.open();
dbUtils.setVisibility(id);
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","yes");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
else
{
try
{
dbUtils.open();
dbUtils.setInVisibility(id);
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","no");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
}
});
convertView.setTag(holder);
}
ViewHolder hold = (ViewHolder) convertView.getTag();
//setting Data to List
hold.textDate.setText(date);
hold.textType.setText(type);
hold.textCost.setText(cost);
if(CheckReceiver.checkAll)
{
hold.togCheck.setChecked(true);
}
if(!CheckReceiver.checkAll)
{
hold.togCheck.setChecked(false);
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
static class ViewHolder{
public CheckBox togCheck;
public TextView textDate;
public TextView textType;
public TextView textCost;
}
}

As Listview recycles view its not possible to do this with only BroadCastReciver. It was really a bad idea.
I done this using Database and BroadCastReciver.
holder.togCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*Intent intent=new Intent();
intent.setAction("clicked")*/;
if(holder.togCheck.isChecked())
{
//holder.togCheck.setBackgroundResource(R.drawable.check);
try
{
dbUtils.open();
dbUtils.setVisibility(id);
// Toast.makeText(context, "Checked ", Toast.LENGTH_SHORT).show();
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","yes");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
else
{
// holder.togCheck.setBackgroundResource(R.drawable.uncheck);
try
{
dbUtils.open();
dbUtils.setInVisibility(id);
Toast.makeText(context, "UnChecked ", Toast.LENGTH_SHORT).show();
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
dbUtils.close();
}
intent.putExtra("isClicked","no");
intent.putExtra("ID",""+id);
context.sendBroadcast(intent);
}
}
});
what i done is i set the checked or unchecked state of checkbox according to id in database.
Then by fetching state of that id i done calculation!.

Related

dynamic listview adding “Load more items” at the end of scroll

I have a listview fetching data from sql database by Json.
I want to turn it into dynamic listview that at the end of scroll, a "load more items" appears in the footer of the list while loading more items and adding them to the adapter (for example 10 items each time). I have problem in implementing this feature. Please help me with it.Thankx.
Activity Class:
public class MoreVideos extends ListActivity {
int i =1;
private int dateCode = 1;
private ListArrayAdapter listAdapter = null;
private ProgressDialog pDialog = null;
private String id;
#SuppressWarnings("unused")
ArrayList<videoDto> aryLists =null;
String getDate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.more_video);
id=getIntent().getStringExtra("id");
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading....");
pDialog.setCancelable(true);
loadCategoriesAsync();
};
// TODO Auto-generated method stub
protected void loadCategoriesAsync() {
loadCategoriesTaskHandler task = new loadCategoriesTaskHandler();
if (Build.VERSION.SDK_INT >= 11)
{
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else
{
task.execute();
}
}
class loadCategoriesTaskHandler extends AsyncTask<videoDto, Void, String>
{
#Override
protected String doInBackground(videoDto... params)
{
String results= "";
try
{
videoDto videodto=new videoDto();
// healthDto.getInfom(strEail.trim(),strPassword,getApplicationContext());
aryLists = new ArrayList<videoDto>();
aryLists= videodto.getvideo(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return results;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(aryLists!=null){
listAdapter = new ListArrayAdapter(getApplicationContext(), MoreVideos.this,
aryLists);
setListAdapter(listAdapter);
}else{
Toast.makeText(getApplicationContext(), "ArrayList is null ", Toast.LENGTH_SHORT).show();
}
}
}
Adapter Class:
public class ListArrayAdapter extends ArrayAdapter<videoDto> {
private final Context context;
private MoreVideos _parent;
public ListArrayAdapter(Context context, MoreVideos parent,
ArrayList<videoDto> aryLog) {
super(context, R.layout.video_listing, aryLog);
this.context = context;
this._parent = parent;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflate.inflate(R.layout.video_listing,
null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.index = (TextView) rowView
.findViewById(R.id.index);
viewHolder.NameOfVideo = (TextView) rowView
.findViewById(R.id.txt_name_video);
viewHolder.img = (ImageView) rowView
.findViewById(R.id.img_video);
viewHolder.rel= (RelativeLayout) rowView.findViewById(R.id.click);
viewHolder.bookv = (ImageView)rowView.findViewById(R.id.bookv);
//viewHolder.download = (ImageView)rowView.findViewById(R.id.download);
rowView.setTag(viewHolder);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
final videoDto userLog = (this._parent != null) ? this._parent.listAdapter
.getItem(position) : null;
String currentPosition = Integer.toString(position);
if (userLog != null) {
try {
try {
/* if(currentPosition.equals(""))
{
holder.index.setText("-----");
}
else
{
holder.index.setText(Integer.toString(Integer.parseInt(currentPosition) + 1));
}*/
holder.rel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name =userLog.link ;
/*try {
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource("http://xty/MRESC/images/test/xy.mp3");
player.prepare();
player.start();
} catch (Exception e) {
// TODO: handle exception
}*/
//Log.v("String ", speaker.vid);
Intent mainIntent = new Intent(getApplicationContext(),VideoViewActivity.class);
mainIntent.putExtra("IMGNAME", name);
//Log.v("name",name);
// startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(name)));
startActivity(mainIntent);
}
});
holder.bookv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// String jobId = (String) v.getTag();
String name =userLog.link ;
videoDto videodto = (videoDto) v.getTag();
Intent intentJobApplicants = new Intent(getApplicationContext(),VideoViewActivity.class);
intentJobApplicants.putExtra("IMGNAME",name);
// intentJobApplicants.putExtra("JobId", jobAp.id);
startActivity(intentJobApplicants);
}
});
if (userLog.VideoText.equals("")) {
holder.NameOfVideo.setText("-----");
} else {
holder.NameOfVideo.setText(userLog.VideoText);
}
i=i+1;
Log.v("i",String.valueOf(i));
} catch (Exception ex) {
// Toast.makeText(context, ex.getMessage(),
// Toast.LENGTH_SHORT).show();
}
if (position % 2 == 0) {
rowView.setBackgroundColor(Color.LTGRAY);
} else {
rowView.setBackgroundColor(Color.WHITE);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
return rowView;
}
}
}
View Holder Class:
public static class ViewHolder {
protected TextView index;
protected ImageView bookv;
protected ImageView img;
protected ImageView download;
protected TextView NameOfVideo;
protected RelativeLayout rel;
}

Change Listview item image on click in Android

i want to change particular listview images when click on nect and prev button but Changed all list view images when click on next and prev button
public class ListAdapter extends ArrayAdapter<String>{
Context context;
String imgurl;
String[] imageUrls;
int i=1;
ViewHolder holder = null;
ArrayList<String> strimgview,strstreetname,strLocation,strSquarefootage,strPrice,strPosted,strURL,strId;
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true).build();
public ListAdapter(Context context,ArrayList<String> strimgview, ArrayList<String> strstreetname,
ArrayList<String> strLocation,ArrayList<String> strSquarefootage,
ArrayList<String> strPrice,ArrayList<String> strPosted,
ArrayList<String> strId,ArrayList<String> strURL)
{
super(context, R.layout.propertyrow,strstreetname);
this.context= context;
this.strimgview= strimgview;
this.strstreetname= strstreetname;
this.strLocation= strLocation;
this.strSquarefootage= strSquarefootage;
this.strPrice= strPrice;
this.strPosted= strPosted;
this.strURL= strURL;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View row = convertView;
if (row == null) {
row=mInflater.inflate(R.layout.propertyrow, parent,false);
holder = new ViewHolder();
holder.imgProperty =(ImageView) row.findViewById(R.id.npTupleImage);
holder.txtStreetName= (TextView) row.findViewById(R.id.npTupleProjectName);
holder.txtLocation= (TextView) row.findViewById(R.id.npTupleBuilder);
holder.txtSquareFotage= (TextView) row.findViewById(R.id.npTupleProjectAddress);
holder.txtPrice =(TextView) row.findViewById(R.id.npTupleProjectDistance);
holder.txtprev =(TextView) row.findViewById(R.id.prev);
holder.txtnext =(TextView) row.findViewById(R.id.next);
//txtprev.setVisibility(View.INVISIBLE);
//txtnext.setVisibility(View.INVISIBLE);
holder.imglike= (ImageView) row.findViewById(R.id.unsavebtn);
holder.imglike.setVisibility(View.INVISIBLE);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
// txtposted.setText("EnteredDate :"+strPosted.get(position));
holder.txtStreetName.setText("Street Name :"+strstreetname.get(position));
holder.txtLocation.setText("Location :"+strLocation.get(position));
holder.txtSquareFotage.setText("SquareFootage :"+strSquarefootage.get(position));
holder.txtPrice.setText("Price :$"+strPrice.get(position));
holder.imgProperty.setTag(position);
// Log.d("Img",strimgview.get(position));
try{
// ArrayList<String> imgurl=new ArrayList<String>();
imgurl= ""+strimgview.get(position);
imageUrls=imgurl.split("\\|\\|");
for(int j=0;j<imageUrls.length-1;j++)
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
}
catch(Exception e)
{
Toast.makeText(context, "Load"+e, Toast.LENGTH_LONG).show();
}
holder.imglike.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(context, "Want to save", Toast.LENGTH_LONG).show();
}
});
holder.txtprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(i!=1)
{
i--;
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
Log.d("imageUrlnew ",imageUrls[i]);
}
}
catch(Exception e)
{
// Toast.makeText(context, "next"+e, Toast.LENGTH_LONG).show();
}
notifyDataSetChanged();
}
});
holder.txtnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if((i<imageUrls.length-1))
{
i++;
imageLoader.displayImage(imageUrls[i], holder.imgProperty, options);
Log.d("imageUrlnew ",imageUrls[i]);
}
}
catch(Exception e)
{
// Toast.makeText(context, "prev"+e, Toast.LENGTH_LONG).show();
}
notifyDataSetChanged();
}
});
return row;
}
class ViewHolder {
ImageView imgProperty;
TextView txtprev,txtnext;
TextView txtStreetName;
TextView txtLocation;
TextView txtSquareFotage;
TextView txtPrice;
ImageView imglike;
ProgressBar progressBar;
}
}
Please help me how can fix this issue
Thanks In Advance
this is not a perfect solution if it works according to ur requirment. then update the solution withot switch.
lstviewHomeList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
switch (position) {
case 0:
Button btnprev = (Button ) arg1.findViewById(R.id.button_id);
//same for image and any widgetn your adapter layout xml
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//do what u want
}
});
break;
default:
break;
}
}
});

handling click of buttons in list view item android

I have a custom list view where each list item has two buttons, one text view and one seek bar where the seek bar visibility is set to gone in list item's XML.
Now what I want to do is on click of button one in the list item I want to hide the text view and display the seek bar of that list item whose button is clicked and show hide the seek bar and display the text view of all other list items.
The code that I have written works well if the total items are less than the views that can be displayed at once in a list view but for a lot of views this does not works.
What I am doing is load a list of files from a a folder into the list view and play the in the list view only
Please tell me where I am going wrong.
Any help would be appreciated.
My Adapter Code:
public class AudioFileListAdapter extends BaseAdapter {
Context context;
ArrayList<String> fileList;
LayoutInflater inflater;
String folder;
ListView mListView;
public MediaPlayer mPlayer;
public Handler seekHandler;
SeekBar mSeekBar;
int clickedPos = -1;
protected static class RowViewHolder {
public TextView fileName;
public Button filePlay;
public Button rate;
public SeekBar fileSeek;
}
public AudioFileListAdapter(Context context, ArrayList<String> fileList,
String folder) {
this.fileList = fileList;
this.context = context;
this.folder = folder;
mListView = (ListView) ((Activity) context)
.findViewById(R.id.Filelistview);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
seekHandler = new Handler();
}
#Override
public int getCount() {
return fileList.size();
}
#Override
public Object getItem(int position) {
return fileList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView
.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView
.findViewById(R.id.file_play);
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView
.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}
OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.file_play)
{
final int position = mListView.getPositionForView((View) v
.getParent());
Log.d("position"+position, "count"+mListView.getCount());
for (int i = 0 ; i < mListView.getChildCount(); i++) {
RowViewHolder viewholder = (RowViewHolder) ((View) mListView
.getChildAt(i)).getTag();
if (i == position) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/analyser/"
+ folder
+ "/"
+ fileList.get(i);
mSeekBar = viewholder.fileSeek;
Log.d("IN the click "+i,path);
// mSeekBar.setEnabled(false);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(mPlayer != null && fromUser){
mPlayer.seekTo(progress);
}
}
});
viewholder.fileSeek.setVisibility(View.VISIBLE);
viewholder.fileName.setVisibility(View.GONE);
play(path);
} else {
viewholder.fileSeek.setVisibility(View.GONE);
viewholder.fileName.setVisibility(View.VISIBLE);
}
}
}
if (v.getId() == R.id.rate) {
}
}
};
public void play(String path) {
if (mPlayer == null) {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mSeekBar.setMax(mPlayer.getDuration());
mp.start();
seekUpdation();
}
});
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
mPlayer = null;
seekHandler.removeCallbacks(run);
}
});
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
seekHandler.removeCallbacks(run);
}
try {
mPlayer.setDataSource(path);
mPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mPlayer != null) {
seekUpdation();
}
}
};
public void seekUpdation() {
if (mPlayer != null) {
mSeekBar.setProgress(mPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
}
}
You have to set the listeners for the button in the Adapter class getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.audio_file_list_item, null);
viewHolder = new RowViewHolder();
viewHolder.fileName = (TextView) convertView.findViewById(R.id.file_name);
viewHolder.filePlay = (Button) convertView.findViewById(R.id.file_play);
viewHolder.filePlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view){
// Do Your Work Here
}
});
viewHolder.filePlay.setTag(position);
viewHolder.rate = (Button) convertView.findViewById(R.id.rate);
viewHolder.fileSeek = (SeekBar) convertView.findViewById(R.id.file_seek);
viewHolder.filePlay.setOnClickListener(mListener);
viewHolder.rate.setOnClickListener(mListener);
convertView.setTag(viewHolder);
} else {
viewHolder = (RowViewHolder) convertView.getTag();
}
viewHolder.fileName.setText(fileList.get(position));
return convertView;
}

Select all listview checkbox when we select the select all checkbox in android

I m using fragment where i m having the ListView and the select all check box.
Fragment class..
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fb_custom_listview = (ListView) selectfriend_login
.findViewById(R.id.friend_listview);
select_all=(CheckBox) selectfriend_login.findViewById(R.id.select_all_checkbox);
select_all.setOnCheckedChangeListener(this);
}
now having the custom adapter class extends Baseadapter
where i m having one ImageView ,one TextView and one checkbox in the layout and inflating the layout in the getview method of the baseadapter class.everything is ok it display image,display text and display the checkbox also.so now when i click the select_all(fragment class) checkbox all the checkbox of custom adapter class should be checked and on unchecked all are unchecked.Here is the class
for custom adapter
public class CustomListAdapter extends BaseAdapter
{
private Context contxt;
private ArrayList<String> user_friend_name;
private ArrayList<String> user_friend_pic_url;
private LayoutInflater inflater;
private int friend_counter=0;
private ChangeUIListner mlistner;
public static ArrayList<Integer> selected_friend_pos;
public static ArrayList<String> selected_friend_uid;
public static ArrayList<String> selected_friend_name;
private List<Model> list;
private ViewHolder viewholder=null;
public CustomListAdapter(Context context,ArrayList<String> user_friend_picurl, List<Model> model) {
// TODO Auto-generated constructor stub
this.contxt=context;
this.list=model;
user_friend_pic_url=user_friend_picurl;
selected_friend_uid=new ArrayList<String>();
selected_friend_name=new ArrayList<String>();
selected_friend_pos=new ArrayList<Integer>();
user_friend_name=GetFriendDetails.user_fb_friend_name;
inflater=(LayoutInflater) contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.gc();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return user_friend_pic_url.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView( int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
viewholder=new ViewHolder();
convertView=inflater.inflate(R.layout.custom_listview_friendlist, null);
viewholder.fb_friend_name=(TextView) convertView.findViewById(R.id.friend_nametextview);
viewholder.fb_friend_pic=(ImageView) convertView.findViewById(R.id.friend_picview);
viewholder.fb_checkbox=(CheckBox) convertView.findViewById(R.id.friendselectcheckBox);
viewholder.fb_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int getposition=(Integer) buttonView.getTag();
Log.e("ITEM POSITION", "."+getposition);
list.get(getposition).setSelected(buttonView.isChecked());
if(isChecked==true)
{
if(selected_friend_pos.contains(getposition))
{
//nothing
}
else
{
friend_counter++;
mlistner.UpdateUi(friend_counter);
selected_friend_pos.add(getposition);
selected_friend_uid.add(GetFriendDetails.user_fb_friend_id.get(getposition));
selected_friend_name.add(GetFriendDetails.user_fb_friend_name.get(getposition));
Log.e("ARRAY SIZE", "."+selected_friend_uid.size());
}
}
else
{
if(selected_friend_pos.contains(getposition)){
friend_counter--;
mlistner.UpdateUi(friend_counter);
int del_posi=selected_friend_pos.indexOf(getposition);
selected_friend_pos.remove(del_posi);
selected_friend_name.remove(del_posi);
selected_friend_uid.remove(del_posi);
Log.e("ARRAYLIST", "REM"+del_posi);
Log.e("ARRAY SIZE", "."+selected_friend_uid.size());
}
}
}
});
convertView.setTag(viewholder);
}
else
{
viewholder=(ViewHolder) convertView.getTag();
new AsyncDownloadImage(viewholder).execute(user_friend_pic_url.get(position));
}
viewholder.fb_checkbox.setTag(position);
viewholder.fb_checkbox.setChecked(list.get(position).isSelected());
viewholder.fb_friend_name.setText(user_friend_name.get(position));
viewholder.fb_friend_name.setTag(user_friend_name.get(position));
viewholder.fb_friend_pic.setTag(user_friend_pic_url.get(position));
//new AsyncDownloadImage(viewholder).execute(user_friend_pic_url.get(position));
return convertView;
}
class ViewHolder
{
int id;
ImageView fb_friend_pic;
TextView fb_friend_name;
CheckBox fb_checkbox;
}
public class AsyncDownloadImage extends AsyncTask<String, Object, Bitmap>
{
private HttpURLConnection connection;
private InputStream is;
private Bitmap bitmap;
private URL url;
ViewHolder holder;
public AsyncDownloadImage(ViewHolder viewholder1) {
// TODO Auto-generated constructor stub
holder=viewholder1;
}
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try {
url=new URL(params[0]);
try {
connection=(HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
is=connection.getInputStream();
bitmap=BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}if(connection!=null)
{
connection.disconnect();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
if(result!=null)
{
holder.fb_friend_pic.setImageBitmap(result);
}
}
}
public void registerUIupdateListener(ChangeUIListner lisnter)
{
mlistner=lisnter;
}
}
as u can see i had used the single selection thing for the listview checkbox so its working fine and adding into arraylist for further operation.so how can we achieve the select all when the check box is click or select.Thanks
When u click selectAll check button then call selectAllFromList(value) function.
like
selectAllButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked())
{
selectAllFromList(true);
}else
{
selectAllFromList(false);
}
}
Following function will select all check boxes from the list:
private void selectAllFromList(boolean b) {
int cList = list.getCount();
for(int i=0;i<cList;i++){
View sView = yourMainList.getChildAt(i);
if(sView != null){
CheckBox childCheckBox=(CheckBox)sView.findViewById(R.id.urCheckButton);
childCheckBox.setChecked(b);
childCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked())
{
selectAllButton.setChecked(false);
}
}
});
}
}
}
});
Hope this one helps you

Remaining item positions in ListView is incorrect after deleting items

I'm having trouble with getting the correct items after deleting an item in my ListView.
The position should fit to the index of the item in an ArrayList, but after deleting an item in the ListView, the positions are incorrect (and might even give an indexoutofbounds exception.
I bet it has something to do with the Views position, but I just can't find the error.
I have this ListActivity class with an inner BaseAdapter class:
public class MSMobilMyStocksActivity extends ListActivity {
static MyStocksCtr myStocksCtr;
static ListView listview;
static EfficientAdapter adap;
boolean downloadSuccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystockslist);
mContext = this;
listview = getListView();
myStocksCtr = MyStocksCtr.getInstance(mContext);
adap = new EfficientAdapter(this);
setListAdapter(adap);
if (isOnline())
new InsertDataTask().execute();
else {
startTimer();
Toast.makeText(mContext, "Du har ingen internetforbindelse", 1000)
.show();
}
}
public static boolean updateData() {
return myStocksCtr.downloadJson();
}
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
try {
listview.setEnabled(false);
} catch (Exception e) {
}
}
// can use UI thread here
#Override
protected void onPostExecute(final Void unused) {
if (isOnline()) {
if (downloadSuccess) {
try {
if (myStocksCtr.getArray().size() == 0) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else if (myStocksCtr.getArray().size() == 1
&& myStocksCtr.getArray().get(0)
.getString("FH_FULLNAME").equals("-")) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else {
adap.notifyDataSetChanged();
}
} catch (JSONException e) {
Toast.makeText(mContext, "JSONException", 2000).show();
}
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
startTimer();
try {
listview.setEnabled(true);
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
downloadSuccess = false;
if (isOnline()) {
try {
if (updateData())
downloadSuccess = true;
} catch (Exception e) {
Toast.makeText(mContext, "Fejl under download af data",
2000).show();
downloadSuccess = false;
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
return null;
}
}
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mylistitem, null);
holder = new ViewHolder();
holder.stockName = (TextView) convertView
.findViewById(R.id.stockName1);
holder.stockPrice = (TextView) convertView
.findViewById(R.id.stockValue1);
holder.stockChange = (TextView) convertView
.findViewById(R.id.stockChange1);
holder.stockPctChange = (TextView) convertView
.findViewById(R.id.stockPctChange1);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent i = new Intent(mContext, MSStockDetailActivity.class);
Bundle b = new Bundle();
b.putInt("position", position); //Your id
b.putBoolean("isMyStocks", true);
i.putExtras(b); //Put your id to your next Intent
mContext.startActivity(i);
} catch (Exception e) {
Toast.makeText(mContext, "OnClick error ", 2000)
.show();
}
}
});
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
final CharSequence[] items = {
"See stock details",
"Delete the stock \"" + holder.stockName.getText()
+ "\" from the list", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setTitle("Configure list");
builder.setItems(items,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int item) {
if (item == 1) {
myStocksCtr.removeStock(holder.ric);
adap.notifyDataSetChanged();
} else if (item == 2) {
}
Toast.makeText(mContext, items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_FULLNAME");
holder.stockName.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_RIC");
holder.ric = result;
} catch (JSONException e) {
e.printStackTrace();
}
// + String.valueOf(position));
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_PRC");
if (String.valueOf(result.charAt(result.length() - 2)).equals(
".")) {
result += "0";
}
;
holder.stockPrice.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
holder.position = position;
return convertView;
}
static class ViewHolder {
String ric;
TextView stockName;
TextView stockPrice;
TextView stockPctChange;
TextView stockChange;
int position;
}
#Override
public Filter getFilter() {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return myStocksCtr.getArray().size();
}
#Override
public JSONObject getItem(int position) {
return myStocksCtr.getArray().get(position);
}
}
This is some of the things in my stocks controller (where the array is):
public class MyStocksCtr {
private static MyStocksCtr INSTANCE = null;
ArrayList<String> myStocksArray;
JSONCtr jsonCtr;
static Context mContext;
boolean isRunning = false;
ArrayList<JSONObject> myArray;
MyStocksCtr(Context mContext) {
this.mContext = mContext;
jsonCtr = new JSONCtr(mContext);
myStocksArray = new ArrayList<String>();
myArray = new ArrayList<JSONObject>();
}
}
public static MyStocksCtr getInstance(Context context){
mContext = context;
if(INSTANCE == null) {
INSTANCE = new MyStocksCtr(mContext);
}
return INSTANCE;
}
public ArrayList<JSONObject> getArray() {
return myArray;
}
public boolean downloadJson() {
if (!myStocksArray.isEmpty()) {
String myStocksString = "";
for (String s : myStocksArray)
myStocksString += (s + "%2C");
myStocksString = myStocksString.substring(0,
myStocksString.length() - 3);
jsonCtr.getJSON(preStocksUrl + myStocksString + postStocksUrl);
myArray.clear();
myArray.addAll(jsonCtr.getArray());
return true;
} else {
return false;
}
}
public void removeStock(String newStock) {
JSONObject toRemove = null;
for (JSONObject obj : myArray) {
try {
if (obj.getString("FH_RIC").equals(newStock)) {
toRemove = obj;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Kunne ikke fjerne objekt", 1000)
.show();
}
}
if (toRemove != null){
myStocksArray.remove(newStock);
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
saveMyStocks();
}
}
}
In my jsonCtr I remove and get the array:
public ArrayList<JSONObject> getArray() {
return rics1;
}
public void removeRic(Object o){
rics1.remove(o);
}
When i have removed an object from the list, the list is updated, so the item is no longer there. But the positions of the views are all messed up, and some of them are outofbounds.
I'm guessing it has something to do with the position in GetView is final, but I'm not sure? And if that is the problem, how do I correct it?
Hmm, I didn't looked at every detail of your code but i think you're missing to call myAdaper.notifyDataSetChanged() after changing your array.
Edit
That*s really tough to look trough because it's a lot of code you post here. So here is what I got. I can't see what's going on in here (on stock remove) but there must be something wrong I think:
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
Please don't post the whole code of that too, try to reduce it to the actual problem. I wont check the whole code again...

Categories

Resources