I have a GridView which shows all the images from phone. I'm able to select multiple images and save the selected images to arraylist. I want to restrict the size of the selected images to 1MB. For that I want to check the size of every image while selecting. If the size of clicked image is less than 1MB then it will get selected, otherwise not. Is there any way to do that?
Activity
public class CustomGalleryActivity extends AppCompatActivity implements View.OnClickListener {
private static Button selectImages;
private static GridView galleryImagesGridView;
private static ArrayList<String> galleryImageUrls;
private static GridViewAdapter imagesAdapter;
int file_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customgallery_activity);
initViews();
setListeners();
fetchGalleryImages();
setUpGridView();
}
//Init all views
private void initViews() {
selectImages = (Button) findViewById(R.id.selectImagesBtn);
galleryImagesGridView = (GridView) findViewById(R.id.galleryImagesGridView);
}
//fetch all images from gallery
private void fetchGalleryImages() {
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order
galleryImageUrls = new ArrayList<String>();//Init array
//Loop to cursor count
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index
System.out.println("Array path" + galleryImageUrls.get(i));
}
}
//Set Up GridView method
private void setUpGridView() {
imagesAdapter = new GridViewAdapter(CustomGalleryActivity.this, galleryImageUrls);
galleryImagesGridView.setAdapter(imagesAdapter);
}
//Set Listeners method
private void setListeners() {
selectImages.setOnClickListener(this);
}
//Show hide select button if images are selected or deselected
public void showSelectButton() {
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
if (selectedItems.size() > 0) {
selectImages.setText(selectedItems.size() + " - Images Selected");
selectImages.setVisibility(View.VISIBLE);
} else
selectImages.setVisibility(View.GONE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.selectImagesBtn:
//When button is clicked then fill array with selected images
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
//Send back result to MainActivity with selected images
Intent intent = new Intent();
intent.putExtra(UploadActivity.CustomGalleryIntentKey, selectedItems.toString());//Convert Array into string to pass data
setResult(RESULT_OK, intent);//Set result OK
finish();//finish activity
break;
}
}
}
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
public GridViewAdapter(Context context, ArrayList<String> imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("sammy_position "+buttonView.getTag());
File f = new File(imageUrls.get((Integer) buttonView.getTag()));
int file_size = Integer.parseInt(String.valueOf(f.length() / (1024*1024)));
// Filtering the image size
if(file_size<1){
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);//Insert selected checkbox value inside boolean array
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}else{
buttonView.setChecked(false);
Toast.makeText(context, "Select image of size 1MB or less", Toast.LENGTH_SHORT).show();
}
}
};
}
public void calculateImageSize(int imageId){
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
imageId);
Bitmap bitmap = bitmapOrg;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
double sizeInKB=(lengthbmp/1024);
double sizeInMB=(lengthbmp/(1024*1024));
Log.d("TAG","Size "+sizeInKB+"KB");
Log.d("TAG","Size "+sizeInMB+"MB");
}
Replace Adapter With this
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import java.util.ArrayList;
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
private boolean isCustomGalleryActivity;
public GridViewAdapter(Context context, ArrayList<String> imageUrls, boolean isCustomGalleryActivity) {
this.context = context;
this.imageUrls = imageUrls;
this.isCustomGalleryActivity = isCustomGalleryActivity;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
//If Context is MainActivity then hide checkbox
if (!isCustomGalleryActivity)
mCheckBox.setVisibility(View.GONE);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag("file://" + imageUrls.get(position));
mCheckBox.setId(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getId(), isChecked);//Insert selected checkbox value inside boolean array
String imagePath = (String) buttonView.getTag();
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}
};
}
Use this function to find out the size in kb & MB
Related
I created a custom adapter for my GridView that will display an image of a book (View image) and its name (View text);
, I declared the list of names of the books in the string file:
[strings.xml]
<string-array name="bookLabels">
<item>android security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>Linux Firewalls</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>Linux Basicsfor Hackers</item>
<item>Black Hat Python</item>
</string-array>
So I want to do the same thing with the images,instead of declaring them in the code like that :
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
I declared the names of the images in a string array named "bookImages",
<string-array name="bookImages">
<item>#drawable/android_security</item>
<item>#drawable/penetration_testing</item>
<item>#drawable/red_team</item>
<item>#drawable/lf</item>
<item>#drawable/the_art_of_exploitation</item>
<item>#drawable/web_application_hacker </item>
<item>#drawable/lbh </item>
<item>#drawable/bhp </item>
</string-array>
and then I recovered the location of all the images declared in to "bookimagesfromstring"array :
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " +
Arrays.toString(bookImagesFromString))
this is the source code of [main activity]
public class main extends AppCompatActivity {
String[] labels;
String[ ] pages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Resources res = getResources();
labels = res.getStringArray(R.array.bookLabels);
pages = res.getStringArray(R.array.web_pages);
GridView gridView = findViewById(R.id.gridView1);
BookGrid myAdapter = new BookGrid(getApplicationContext(), labels);
gridView.setAdapter(myAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.gridtextView))
.getText(), Toast.LENGTH_SHORT).show();
// Intent webPageIntent = new Intent(getApplicationContext(),
DisplayWebPage.class);
// webPageIntent.putExtra("WEB_PAGE", pages[ position ] );
// startActivity( webPageIntent );
}
});
}
}
And the [ BookGrid Class ]
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromString;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " + Arrays.toString(bookImagesFromString));
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
//To Avoid ArrayIndexOutOfBoundsException
//boolean inBounds = (position >= 0) && (position <= imageName.length);
txtv.setText(imageName[position]);
//imgv.setImageResource(bookImagesFromString[position]);
imgv.setImageResource(bookImages[position]);
} else {
}
return convertView;
}
the result for the "bookImagesFromString" array was as follows :
([res/drawable-v24/android_security.png, res/drawable-v24/penetration_testing.png, res/drawable-v24/red_team.png, res/drawable/lf.jpg, res/drawable-v24/the_art_of_exploitation.png, res/drawable-v24/web_application_hacker.png, res/drawable/lbh.png, res/drawable-v24/bhp.png])
So the question is how to convert the "bookImagesFromString" array to an array that contains the ID of each image ? -And after using it in this code part:
imgv.setImageResource(bookImagesID[position]);
Thanks.
Try string array like this:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>lbh</item>
<item>bhp</item>
</string-array>
and adapter like this:
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private Integer[] bookImages;
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
Resources resi = context.getResources();
String[] bookImagesFromString = resi.getStringArray(R.array.bookImages);
bookImages = new Integer[bookImagesFromString.length];
for (int i = 0; i < bookImagesFromString.length; i++) {
bookImages[i] = (resi.getIdentifier(bookImagesFromString[i], "drawable", context.getPackageName()));
}
}
#Override
public int getCount() {
return imageName.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
}
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
imgv.setImageResource(bookImages[position]);
return convertView;
}
}
Hope that helps!
for the name of the images as I_A_Mok said I took just:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker </item>
<item>lbh </item>
<item>bhp </item>
</string-array>
So I had two solutions :
A method with Context:
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
Or without Context (this approach is faster than the first Retrieving Resources in Android) :
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
and here is the complete code
package com.example.gridview.BookGridWebView;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.gridview.R;
import java.lang.reflect.Field;
import java.util.Arrays;
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromStringArray;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
bookImagesFromStringArray =
context.getResources().getStringArray(R.array.bookImageName);
//the table contains the IDs of each Image
Integer[] bookIDs = getIds(context,bookImagesFromStringArray);
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
// imgv.setImageResource(bookImages[position]);
imgv.setImageResource(bookIDs[position]);
} else {
}
return convertView;
}
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
}
Thanks.
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
I created custom ListView with CheckBox next to title. I want to get checked
CheckBox from ListView
I created following function for get message from ListView and send it to another ListView with Intent but I cant get the particular CheckBox position to move.
public class SpamActivity extends AppCompatActivity {
List<Message> sms;
ArrayList<Message> sms1;
ArrayList<String> al;
ListView lv;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
lv= (ListView) findViewById(R.id.lvMsg);
checkbox = (CheckBox) findViewById(R.id.checkBox);
sms = new ArrayList<>();
al=new ArrayList<>(0);
populateMessageList();
/* SpamActivity spamactivity = new SpamActivity();
al = spamactivity.al;
//InboxFragment inboxfragment = new InboxFragment();
//al = inboxfragment.list;
for (int i=0;i<sms.size();i++){
System.out.println("AddressSPS" + sms.get(i));
} */
Collections.reverse(sms);
}
public void populateMessageList() {
sms1 = new ArrayList<>();
fetchDatabaseMessage();
lv.setAdapter(new datalist(getApplicationContext(), sms1));
// to handle click event on listView item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// when user clicks on ListView Item , onItemClick is called
// with position and View of the item which is clicked
// we can use the position parameter to get index of clicked item
TextView textViewSMSSender = (TextView) v.findViewById(R.id.lblNumber);
TextView textViewSMSBody = (TextView) v.findViewById(R.id.lblMsg);
TextView textViewSMSDate = (TextView) v.findViewById(R.id.smsdate);
String smsSender = textViewSMSSender.getText().toString();
String smsBody = textViewSMSBody.getText().toString();
String smsDate = textViewSMSDate.getText().toString();
Intent intentspam = new Intent(getApplicationContext(), DisplaySpamsms.class);
intentspam.putExtra("number",smsSender);
intentspam.putExtra("msg",smsBody);
startActivity(intentspam);
}
});
}
// This method featch the message stored in database
public void fetchDatabaseMessage(){
DB_Message dbmessage = new DB_Message(this);
sms = dbmessage.ViewMessageData();
String addr = sms.get(0).getmAddress();
if (addr.equals(sms.get(0).getmAddress())) {
for (int i = 0; i < sms.size(); i++) {
al.add(sms.get(i).getmAddress());
//al.add(sms.get(i).getmBody());
}
}else {
System.out.println("SMS Not Displayed");
}
}
class datalist extends BaseAdapter {
Context context;
ArrayList<Message> arrayListsms;
public datalist(Context context, ArrayList<Message> arrayListsms) {
// TODO Auto-generated constructor stub
this.context = context;
this.arrayListsms = arrayListsms;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return sms.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = getLayoutInflater();
View row;
row = inflator.inflate(R.layout.row, parent, false);
// ImageView img1 = (ImageView) row.findViewById(R.id.imageView1);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
final TextView txt1 = (TextView) row.findViewById(R.id.lblMsg);
final TextView txt2 = (TextView) row.findViewById(R.id.lblNumber);
final TextView txt3 = (TextView) row.findViewById(R.id.smsdate);
//Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
//mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText(sms.get(position).getmAddress());
//+"\n"+mformatter.format(mcalendar.getTime())
txt3.setText(mformatter.format(mcalendar.getTime()));
final String msgBody = txt1.getText().toString();
final String msgAddr = txt2.getText().toString();
final String msgDate = txt3.getText().toString();
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Message msg = new Message();
if (isChecked) {
// selectedStrings.add(tv.getText().toString());
Toast.makeText(context, "" + msgBody, Toast.LENGTH_LONG).show();
System.out.println("Body" + msgBody);
System.out.println("Address" + msgAddr);
System.out.println("Date" + msgDate);
al.add(msgBody + msgAddr + msgDate);
// al.add(msgAddr);
// al.add(msgDate);
sms.remove(position);
ContentValues values = new ContentValues();
values.put("address", sms.get(position).getmAddress());
values.put("body", sms.get(position).getmBody());
String date = msg.getmDate();
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
notifyDataSetChanged();
} else {
// selectedStrings.remove(tv.getText().toString());
}
}
});
return row;
}
}
}
When I used above function for sending message but error is that when I click on any CheckBox to send that message then automatically Different Message is sent to another activity. so, I want to get particular message position to sent it.
You can set "setOnItemClickListener" on list view and get the position.
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here you can get the position
}
});
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class SharedContactListAdapter extends ArrayAdapter<ContactSynResponse> {
private Context context;
private ViewHolder viewHolder;
private SparseBooleanArray mSparseBooleanArray;
private List<ContactSynResponse> mList;
public SharedContactListAdapter(Context context, int resource,
List<ContactSynResponse> objects) {
super(context, resource, objects);
this.context = context;
mSparseBooleanArray = new SparseBooleanArray();
// mList = objects;
}
#Override
public ContactSynResponse getItem(int position) {
return super.getItem(position);
}
public ArrayList<ContactSynResponse> getCheckedItems() {
ArrayList<ContactSynResponse> mTempArry = new ArrayList<ContactSynResponse>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
ContactSynResponse data = mList.get(i);
mTempArry.add(data);
}
}
return mTempArry;
}
class ViewHolder {
ImageView profilepic;
ChimmerTextView contactname;
ChimmerTextView contactno;
RelativeLayout completelayout;
CheckBox selectcheckbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.sharedcontactlistdata,
parent, false);
viewHolder = new ViewHolder();
viewHolder.profilepic = (ImageView) convertView
.findViewById(R.id.profilepic_image_view);
viewHolder.contactname = (ChimmerTextView) convertView
.findViewById(R.id.contactnameTV);
viewHolder.contactno = (ChimmerTextView) convertView
.findViewById(R.id.contactnoTV);
viewHolder.completelayout = (RelativeLayout) convertView
.findViewById(R.id.completeRL);
viewHolder.selectcheckbox = (CheckBox) convertView
.findViewById(R.id.contact_checkbox);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContactSynResponse data = getItem(position);
viewHolder.contactname.setText(data.getName());
viewHolder.contactno.setText(data.getPhone());
viewHolder.selectcheckbox.setTag(position);
viewHolder.selectcheckbox.setOnCheckedChangeListener(new CheckListener(
data, viewHolder.selectcheckbox));
viewHolder.completelayout.setOnClickListener(new ClickListener(data,
viewHolder.selectcheckbox));
return convertView;
}
class CheckListener implements OnCheckedChangeListener {
private CheckBox checkbox;
public CheckListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
} else {
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
}
buttonView.setChecked(isChecked);
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
}
class ClickListener implements OnClickListener {
private CheckBox checkbox;
public ClickListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onClick(View v) {
if (checkbox.isSelected()) {
checkbox.setChecked(false);
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), false);
} else {
checkbox.setChecked(true);
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), true);
}
}
}
}
I am displaying images from the gallery to my custom grid view with checkbox.
I have to select 6 images only.
I have the following code
public class MultiPhotoSelectActivity extends BaseActivity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
CheckBox mCheckBox;
int pos;
ArrayList<String> selectedItems;
ArrayList<String> selectedimgs = new ArrayList<String>();
RelativeLayout rl_gallery_row,rl_gallery_async;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
//Bundle bundle = getIntent().getExtras();
//imageUrls = bundle.getStringArray(Extra.IMAGES);
rl_gallery_async = (RelativeLayout) findViewById(R.id.RelativeLayout_galleryas);
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => "+imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.build();
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(imageAdapter);
/*gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImageGalleryActivity(position);
}
});*/
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public void btnChoosePhotosClick(View v){
selectedItems = imageAdapter.getCheckedItems();
Toast.makeText(MultiPhotoSelectActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
Log.d(MultiPhotoSelectActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString());
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for(int i=0;i<mList.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
}
mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
rl_gallery_row = (RelativeLayout) findViewById(R.id.Relativelayout_gallery_row);
imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(Bitmap loadedImage) {
Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
});
mCheckBox.setTag(position);
//mCheckBox.setId(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
//mCheckBox.setId(position);
//holder.imageview.setId(position);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
selectedItems = imageAdapter.getCheckedItems();
if(selectedItems.size() > 5 )
{
mCheckBox.setEnabled(false); // disable checkbox
}
}
};
}
}
Now i am not able to uncheck the checkbox automatically when the limit is crossed..
Please help..
I think your condition is not satisfied for unchecking the check box, try to put a toast inside your condition
I have implemented a custom adapter class for controlling my listview. I'm implementing a button, a textbox and a checkbox against each row in the listview. I have a couple of buttons that are not part of the listview. They are below the listview. Now when I check any number of boxes and press the button that is not part of the listview, I want to be able to delete the checked boxes (if there are any). In other words, I want to b able to delete the checked items with the click of a button that is not part of the listview.
Here's my main class...
public class ASvideofiles extends Activity implements OnClickListener {
int count = 0;
private String[] vidNames;
private String[] vidPaths;
private ListView myList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asvideofiles);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
File f = new File(Environment.getExternalStorageDirectory(),
"ABC/XYZ/");
File[] files = f.listFiles();
vidNames = new String[files.length];
vidPaths = new String[files.length];
if(files != null) {
for(int i=0; i < files.length; i++) {
vidNames[i] = files[i].getName();
vidPaths[i] = files[i].getPath();
count ++;
}
}
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(vidNames[i]);
}
myList = (ListView)findViewById(R.id.listView1);
myList.setAdapter(new AScustomadapter(ASvideofiles.this, list));
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1) {
} else if(v.getId() == R.id.button2) {
}
}
}
Here's my Adapter class...
public class AScustomadapter extends BaseAdapter {
private ArrayList<String> mListItems;
private LayoutInflater mLayoutInflater;
int i = 0;
private ArrayList<Integer> checkedIndices = new ArrayList<Integer>();
public AScustomadapter(Context context, ArrayList<String> arrayList) {
mListItems = arrayList;
//get the layout inflater
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mListItems.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public int getTotalCheckedCount() {
return checkedIndices.size();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.list_item, null);
holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
holder.cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
}
final String stringItem = mListItems.get(position);
if (stringItem != null) {
if (holder.itemName != null) {
holder.itemName.setText(stringItem);
}
}
holder.cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if(checkedIndices.contains(position)){
}else {
checkedIndices.add(position);
}
}else {
checkedIndices.remove((Integer)position);
}
}
});
if(checkedIndices.contains((Integer)position)) {
holder.cb1.setChecked(true);
} else {
holder.cb1.setChecked(false);
}
//this method must return the view corresponding to the data at the specified position.
return view;
}
private static class ViewHolder {
protected TextView itemName;
protected CheckBox cb1;
}
}
The rows are basically populated with videos, so all in all, I want to be able to delete the selected videos against which the check boxes are checked and the delete button is pressed. Help required. Thanks in advance.
Maintain a Boolean Array which keeps track of the position of the rows of checked CheckBoxes.
Then in your Button onClickListener remove those items from the ArrayList and pass this updated ArrayList to your adapter.
Finally call notifyDataSetChanged()
Here , i have a solution for you. I have added your adapter class in the main activity itself. Basically i have created two array list of type string. When you check a checkbox, the corresponding textview value is stored in it the list CHECKEDLIST. In the other list ALLVALUES, all the values are stored.
On button click i match both the lists and if a match occurs, then i remove that value from ALLVALUES and call notifydatasetchanged
package com.example.test;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MainActivity extends Activity implements OnClickListener {
private ArrayList<String> checkedIndices = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
AScustomadapter adapter;
int count = 0;
private String[] vidNames = {"a","b","c","d","e","f","g","h","i"};
private ListView myList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
for (int i = 0; i < vidNames.length; i++) {
list.add(vidNames[i]);
}
myList = (ListView)findViewById(R.id.list);
adapter = new AScustomadapter(getApplicationContext(), list);
myList.setAdapter(adapter);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1) {
for (int i = 0; i < checkedIndices.size(); i++) {
for(int j = 0; j <list.size();j++){
if(list.get(j).contains(checkedIndices.get(i))){
list.remove(j);
}
}
}
adapter.notifyDataSetChanged();
}
}
public class AScustomadapter extends BaseAdapter {
private ArrayList<String> mListItems;
private LayoutInflater mLayoutInflater;
int i = 0;
public AScustomadapter(Context context, ArrayList<String> arrayList) {
mListItems = arrayList;
//get the layout inflater
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mListItems.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public int getTotalCheckedCount() {
return checkedIndices.size();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.list_item, null);
holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
holder.cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
}
final String stringItem = mListItems.get(position);
if (stringItem != null) {
if (holder.itemName != null) {
holder.itemName.setText(stringItem);
}
}
holder.cb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
if(!checkedIndices.contains(getItem(index).toString()))
checkedIndices.add(getItem(index).toString()); }
else {
checkedIndices.remove(getItem(index).toString());
}
//case 2
}
});
if(checkedIndices.contains((Integer)position)) {
holder.cb1.setChecked(true);
} else {
holder.cb1.setChecked(false);
}
//this method must return the view corresponding to the data at the specified position.
return view;
}
private class ViewHolder {
protected TextView itemName;
protected CheckBox cb1;
}
}
}