Selecting multiple items from custom list view and passing to another
list view. When I close the application, these selected items are getting clean.
I have used shared preference ,I could not able to get the data>
MainActivity
MainActivity.java
public class MainActivity extends Activity {
private Button bt_inst_app;
GridView gridView, gv_shortcut;
List<AppList> installedApps;
List<AppList> res = new ArrayList<AppList>();
private String appName, appPackageName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
gv_shortcut = (GridView) findViewById(R.id.gv_shortcut);
bt_inst_app = (Button) findViewById(R.id.bt_inst_app);
bt_inst_app.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder quick_links_alert = new AlertDialog.Builder(MainActivity.this);
quick_links_alert.setTitle("Edit Quick Links");
LinearLayout quick_links_layout = new LinearLayout(MainActivity.this);
quick_links_layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams quick_links_layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
quick_links_layoutparams.setMargins(20, 0, 30, 0);
gridView = new GridView(MainActivity.this);
installedApps = getInstalledApps();
final GridViewAdapter gridViewAdapter = new GridViewAdapter(MainActivity.this, installedApps);
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(gridViewAdapter);
gridView.setNumColumns(5);
quick_links_alert.setView(gridView);
quick_links_alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final List<AppList> mArrayProducts = gridViewAdapter.getCheckedItems();
final QuickLinksGridViewAdaptor selected_apps = new QuickLinksGridViewAdaptor(MainActivity.this, mArrayProducts);
gv_shortcut.setAdapter(selected_apps);
gv_shortcut.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = mArrayProducts.get(position).getPackageName();
Intent PackageManagerIntent = getPackageManager().getLaunchIntentForPackage(s);//Here some time getting NULL
startActivity(PackageManagerIntent);
}
});
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
quick_links_alert.show();
}
private List<AppList> getInstalledApps() {
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
//if ((isSystemPackage(p) == false)) {
if (((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
appPackageName = p.applicationInfo.packageName;
res.add(new AppList(icon, appName, appPackageName));
}
}
return res;
}
});
}
}
GridViewAdapter.java
public class GridViewAdapter<T> extends BaseAdapter {
Context mContext;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
private int selectedColor = Color.parseColor("#1b1b1b");
SparseBooleanArray mSparseBooleanArray;
SharedPreferences settings;
public GridViewAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return listStorage.size();
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.add_apps_grid_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type);
listViewHolder.tvPkgName = (TextView) convertView.findViewById(R.id.tvPack);
listViewHolder.select_app = (CheckBox) convertView.findViewById(R.id.select_app);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.tvPkgName.setText(listStorage.get(position).getPackageName());
listViewHolder.select_app.setTag(position);
listViewHolder.select_app.setChecked(mSparseBooleanArray.get(position));
final AppList item = listStorage.get(position);
listViewHolder.textInListView.setText(item.getName());
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.getName(), false);
listViewHolder.select_app.setChecked(Checked);
listViewHolder.select_app.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(mContext, "pkg name==" + listStorage.get(position).getPackageName(), Toast.LENGTH_LONG).show();
if (listViewHolder.select_app.isChecked() == true) {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
// Toast.makeText(mContext, "You deselected " + Context.MODE_PRIVATE, Toast.LENGTH_SHORT).show();
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), true).commit());
// Toast.makeText(mContext, "You selected " + item.getName(), Toast.LENGTH_SHORT).show();
} else {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), false).commit());
// Toast.makeText(mContext, "You deselected " + item.getName(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(mContext, "Shared prefernce---->" + mContext.toString(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
static class ViewHolder {
TextView textInListView, tvPkgName;
ImageView imageInListView;
CheckBox select_app;
}
}
AppList.java
public class AppList implements Parcelable {
private String name;
private String packageName;
Drawable icon;
private boolean selected;
public AppList(Drawable icon, String name, String packageName) {
this.name = name;
this.icon = icon;
this.packageName = packageName;
}
protected AppList(Parcel in) {
name = in.readString();
packageName = in.readString();
selected = in.readByte() != 0;
}
public static final Creator<AppList> CREATOR = new Creator<AppList>() {
#Override
public AppList createFromParcel(Parcel in) {
return new AppList(in);
}
#Override
public AppList[] newArray(int size) {
return new AppList[size];
}
};
public String getName() {
return name;
}
public String getPackageName() {
return packageName;
}
public Drawable getIcon() {
return icon;
}
public String toString() {
return name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(packageName);
parcel.writeByte((byte) (selected ? 1 : 0));
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
QuickLinksGridViewAdaptor.java
public class QuickLinksGridViewAdaptor<T> extends BaseAdapter {
private Context context;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
SparseBooleanArray mSparseBooleanArray;
int num = 1;
public QuickLinksGridViewAdaptor(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
//return 8;
if(num*8 >= listStorage.size()){
return listStorage.size();
}else{
return num*8;
}
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.add_apps_grid_item1, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name1);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type1);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
return convertView;
}
static class ViewHolder {
TextView textInListView;
ImageView imageInListView;
}
}
You can either use savedInstanceState method to save and retrieve data in an Activity or You can save the boolean check value every time you change the value of your selection(either selected or non selected state) into SharedPreferences using key as name/id of the value to be selected, and value as true or false.
You can easily check the shared preferences then, to check whether this value is present in shared preferences or not. And use Boolean value to show the selection.
Hope you get this answer.
Related
I have an app which contain two arraylist namely "a" and "b" when I want to disable toggle button of items from arraylist "a" it automatically disable all other items in listview . Please help me out.
code of adapter:-
private LayoutInflater layoutInflater;
private List<AllAppList> listStorage;
private Context mContext;
ArrayList<WhiteListModel> newDataSet, existingDataSet;
private String TAG = AppAdapter.class.getSimpleName();
private MySharedPreference sharedPreference;
private WhiteListModel whiteListModel;
private Gson gson;
public AppAdapter(Context context, List<AllAppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
existingDataSet = new ArrayList<>();
newDataSet = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(mContext);
whiteListModel = new WhiteListModel();
//retrieve data from shared preference
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
boolean isChecked = false;
AllAppList model = listStorage.get(position);
if (existingDataSet!=null){
for (int i = 0; i < existingDataSet.size(); i++) {
if (model.getPackName().equalsIgnoreCase(existingDataSet.get(i).getPackName())) {
isChecked = true;
}
}
}
listViewHolder.switchCompat.setChecked(true);
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
if (isChecked){
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
if (existingDataSet != null) {
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
} else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
//Notifying adapter data has been changed.....
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}else {
listViewHolder.switchCompat.setChecked(true);
}
}
});
return convertView;
}
/**
* Save list of scores to own sharedpref
*
* #param whiteListApps
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> whiteListApps) {
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(whiteListApps);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveAppsArrayListData(jsonScore);
}
private static class ViewHolder {
static SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
Declare Boolean variable in WhiteListModel class. and write getter setter.
In your code add these lines.
private SparseBooleanArray sparseBooleanArray = new SparseBooleanArray();
In getView()
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
**sparseBooleanArray.put(position,whiteListModel.getIsSwitchOn());**
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
boolean isChecked = false;
AllAppList model = listStorage.get(position);
if (existingDataSet!=null){
for (int i = 0; i < existingDataSet.size(); i++) {
if (model.getPackName().equalsIgnoreCase(existingDataSet.get(i).getPackName())) {
isChecked = true;
}
}
}
**listViewHolder.switchCompat.setChecked(whiteListModel.getIsSwitchOn());**
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
if (isChecked){
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
**whiteListModel.setIsSwitchOn(isChecked);**
if (existingDataSet != null) {
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
} else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
//Notifying adapter data has been changed.....
**listViewHolder.switchCompat.setChecked(whiteListModel.getIsSwitchOn());**
notifyDataSetChanged();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
**listViewHolder.switchCompat.setChecked(whiteListModel.getIsSwitchOn());**
}
}).show();
}else {
**listViewHolder.switchCompat.setChecked(whiteListModel.getIsSwitchOn());**
}
}
});
return convertView;
}
If you used a static component in ViewHolder ,it means you want to create only one instance of that object.
So, in this case all buttons are only ONE Button.If you change each property of each row ,It will be change in all rows.
Use this viewHolder instead of your "viewHolder"
private class ViewHolder {
SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
I am facing problem in ListView with selecting and then deselecting Checkbox. I have a button in which i am bypassing all the selected items of a list. But i check and then uncheck, it returned as checked.I am using sparse boolean array.
Here is my code-
#Override
public void onClick(View v) {
if(addProductAdapter.mCheckedState.size()==0){
Toast toast = Toast.makeText(this,SELECT_PRODUCTS, Toast.LENGTH_LONG);
toast.show();
}
else{
ArrayList<Object> list = new ArrayList<Object>();
for (int i = 0; i < addProductAdapter.getCount(); i++) {
if (addProductAdapter.mCheckedState.get(i) == true) {
//ArrayList<Object> list = new ArrayList<Object>();
// for(int j = 0;j<=productObject.size();j++){
ProductEntity productEntity = (ProductEntity) productObject
.get(i);
ProductsEntity pe = new ProductsEntity();
pe.setProcdut_name(productEntity.getName());
pe.setUnit_price(productEntity.getUnitPrice());
pe.setTotal_price(productEntity.getUnitPrice());
pe.setQuantity("1");
list.add(pe);
// arrayList.add(list);
}
}
Intent returnIntent = new Intent();
returnIntent.putExtra(RESULT, list);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
here is my adapter class`private Context context;
private int resourceId;
private List<Object> objArrayList;
public SparseBooleanArray mCheckedState;
public AddProductsAdapter(Context context, int resource, List<Object> objList ) {
super(context, resource,objList);
this.context = context;
this.resourceId = resource;
mCheckedState = new SparseBooleanArray(objList.size());
this.objArrayList = objList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View productview = convertView;
ProductHolder productHolder;
if (productview == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
productview = inflater.inflate(resourceId, parent, false);
productHolder = new ProductHolder();
productHolder.productNameView = (TextView) productview.findViewById(R.id.nameProductView);
productHolder.productIdView = (TextView) productview.findViewById(R.id.IdProductView);
productHolder.productPriceView = (TextView) productview.findViewById(R.id.priceProductView);
productHolder.checkBox = (CheckBox) productview.findViewById(R.id.checkBoxView);
productview.setTag(productHolder);
productview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProductHolder productHolder = (ProductHolder) v.getTag();
if (productHolder.checkBox.isChecked()){
productHolder.checkBox.setChecked(false);
}
else{
productHolder.checkBox.setChecked(true);
}
}
});
}
else{
productHolder = (ProductHolder) productview.getTag();
}
try {
if(objArrayList!=null){
ProductEntity productEntity= (ProductEntity) objArrayList.get(position);
String productName = productEntity.getName();
String productId = productEntity.getProductId();
String productPriceStandrd = productEntity.getStandard();
productHolder.productNameView.setText(productName);
productHolder.productIdView.setText(productId);
productHolder.productPriceView.setText(productPriceStandrd);
//productHolder.checkBox.setTag(position);
productHolder.checkBox.setTag(position);
productHolder.checkBox.setChecked(mCheckedState.get(position, false));
productHolder.checkBox.setOnCheckedChangeListener(this);
}
}
catch (Exception e) {
e.printStackTrace();
}
return productview;
}
public boolean isChecked(int position) {
return mCheckedState.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckedState.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public int getCount() {
return objArrayList != null ? objArrayList.size() : 0;
}
private class ProductHolder {
TextView productNameView;
TextView productIdView;
TextView productPriceView;
CheckBox checkBox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckedState.put((Integer) buttonView.getTag(), isChecked);
}
`
Hi In the below code by using ischecked I want to return the array of checkbox values I want to return.
But How to pass the parameter only checked values in creategroup method.Instead of check which string I have to pass as a parameter.
GroupList.java
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
boolean isChecked;
String check;
ListView users;
int position;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friend = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friend = friends;
}
public int getCount() {
return friend.length;
}
public FriendInfo getItem(int position) {
return friend[position];
}
public long getItemId(int position) {
return 0;
}
#SuppressWarnings("unused")
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox)convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friend[position].userName);
holder.icon.setImageBitmap(friend[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
final ArrayList<String> checkedFriends = new ArrayList<String>();
checkBoxState = new boolean[friend.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
if(isChecked){
check=friend[position].userName;
}
}
});
return convertView;
}
public ArrayList<FriendInfo> getCheckedItems(){
ArrayList<FriendInfo> result = new ArrayList<FriendInfo>();
if(checkBoxState!=null){
for (int i = 0; i < checkBoxState.length; i++) {
if(checkBoxState[i]){
result.add(getItem(i));
}
}
}
return result;
}
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
Button create=(Button)findViewById(R.id.create);
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings({ "unused", "unchecked" })
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
String result1 = imService.CreateGroup(groupname,imService.getUsername(),check);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
friendAdapter = new FriendListAdapter(this);
friendAdapter.getCheckedItems();
}
You can add this method to your adapter:
public ArrayList<FriendInfo> getCheckedItems(){
ArrayList<FriendInfo> result = new ArrayList<FriendInfo>();
if(checkBoxState!=null){
for (int i = 0; i < checkBoxState.length; i++) {
if(checkBoxState[i]){
result.add(getItem(i));
}
}
}
return result;
}
To call it: friendAdapter.getCheckedItems();
UPDATE :
So your code will be like that:
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
boolean isChecked;
String check;
ListView users;
int position;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friend = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friend = friends;
}
public int getCount() {
return friend.length;
}
public FriendInfo getItem(int position) {
return friend[position];
}
public long getItemId(int position) {
return 0;
}
#SuppressWarnings("unused")
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox)convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friend[position].userName);
holder.icon.setImageBitmap(friend[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
final ArrayList<String> checkedFriends = new ArrayList<String>();
checkBoxState = new boolean[friend.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
if(isChecked){
check=friend[position].userName;
}
}
});
return convertView;
}
public ArrayList<FriendInfo> getCheckedItems(){
ArrayList<FriendInfo> result = new ArrayList<FriendInfo>();
if(checkBoxState!=null){
for (int i = 0; i < checkBoxState.length; i++) {
if(checkBoxState[i]){
result.add(getItem(i));
}
}
}
return result;
}
}
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
Button create=(Button)findViewById(R.id.create);
friendAdapter = new FriendListAdapter(this);
/*
* here you must load list items before calling
* "getCheckedItems()", I think you use "setFriendList(...)" for that
* so you need to do friendAdapter.setFriendList(YOUR_LIST). Otherwise you will have an empty array
* because there is no items, so no checked items too.
*/
friendAdapter.getCheckedItems();
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings({ "unused", "unchecked" })
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
/*
* you can also call "getCheckedItems()" here,
* to send the checkedItems to "imService"
*/
String result1 = imService.CreateGroup(groupname,imService.getUsername(),check);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
}
I am android developer, I have a custom listview with a checkbox. This layput also contain a delete button. I want when I click on cheakbox all the item in a particular row is selected and on click of delete it is deleted.
The problem is when I click on delete button I get a list of +1 row value.
Initially I already define :
int position=0;
btmsgdelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("request send for message delete");
for(Message msg:almsg) {
if(msg.isSelected()) {
CheckBox chk = (CheckBox)findViewById(R.id.checkBox1);
System.out.println("msg is selected");
msgid=almsg.get(position).getEmpid();
System.out.println(msgid);
empname=almsg.get(position).getEmpname();
System.out.println(empname);
msgheader=almsg.get(position).getHeader();
System.out.println(msgheader);
}
}
Try this sample code
public class MainActivity extends Activity {
private int textViewResourceId;
private ArrayList<CompareListData> searchResults;
private ListView lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchResults = GetSearchResults();
lst = (ListView) findViewById(R.id.list);
findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < searchResults.size(); i++) {
if (searchResults.get(i).getSelected()) {
searchResults.remove(i);
}
}
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
});
System.out.println("size " + searchResults.size());
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
private ArrayList<CompareListData> GetSearchResults() {
ArrayList<CompareListData> results = new ArrayList<CompareListData>();
CompareListData sr1 = new CompareListData();
sr1.setName("John Smith");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Jane Doe");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Steve Young");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Fred Jones");
results.add(sr1);
return results;
}
}
CompareListData.java
public class CompareListData {
String name;
boolean selected;
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Adapter.java
public class Adapter extends BaseAdapter{
public static int count = 0;
public LayoutInflater inflater;
public static ArrayList<CompareListData> selectedId;
public ArrayList<CompareListData> listObjects;
Context contex;
public Adapter(Context context, int textViewResourceId,
ArrayList<CompareListData> objects) {
super();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listObjects = objects;
this.contex = context;
}
public static class ViewHolder
{
TextView txtViewLoanName;
CheckBox chkSelected;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView==null)
{
final ViewHolder holder = new ViewHolder();
view = inflater.inflate(R.layout.row_comparelist, null);
holder.txtViewLoanName= (TextView) view.findViewById(R.id.rowcomparelist_tv_loanname);
holder.chkSelected= (CheckBox) view.findViewById(R.id.rowcomparelist_chk_selected);
holder.chkSelected.setId(position);
holder.chkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CompareListData element = (CompareListData) holder.chkSelected.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(holder);
holder.chkSelected.setTag(listObjects.get(position));
}
else{
view = convertView;
((ViewHolder) view.getTag()).chkSelected.setTag(listObjects.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtViewLoanName.setText(listObjects.get(position).getName());
holder.chkSelected.setChecked(listObjects.get(position).getSelected());
return view;
}
public int getCount() {
return listObjects.size();
}
public Object getItem(int position) {
return listObjects.get(position);
}
public long getItemId(int position) {return position;
}
}
Hey people I'm Implementing TreeView using ExpandableListView. But I have some measure problem that I unfortunately can't solve it.
Here's ScreenShots of the problem:
You can see that there are problems in measuring. As long as I'm new to Android I don't really understand onMeasure() method.
I have 1 ExpandableListView and in it's getChildView() i return CustomExapndableListView-s.
Here's code:
ExpandableListAdapter :
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listDataChild;
public ExpandableListAdapter (Context context, List<String> listDataHeader, HashMap<String, List<String>> listChildData) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listDataChild = listChildData;
}
#Override
public int getGroupCount() {
return this.listDataHeader.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.listDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
Log.i("Header: ", " " + headerTitle);
if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
/*final String childText = (String) getChild(groupPosition, childPosition);
if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);*/
String childText = (String) getChild(groupPosition, childPosition);
if(listDataChild.containsKey(childText)){
Log.i("Child", "" + childText);
CustomExpandableListView explv = new CustomExpandableListView(context);
// explv.setRows(calculateRowCount((String)getGroup(groupPosition), null));
// ChildLayerExpandableListAdapter adapter = new ChildLayerExpandableListAdapter(context, listDataChild.get(getGroup(groupPosition)), listDataChild);
Log.i("Opaaaa:", " " + getGroup(groupPosition));
List<String> newHeaders = new ArrayList <String>();
newHeaders.add(childText);
// listDataChild.get(getGroup(groupPosition))
ExpandableListAdapter adapter = new ExpandableListAdapter(context, newHeaders, listDataChild);
explv.setAdapter(adapter);
explv.setGroupIndicator(null);
convertView = explv;
convertView.setPadding(20, 0, 0, 0);
}else{
// if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
// }
Log.i("Else:", " " + childText);
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
convertView.setPadding(20, 0, 0, 0);
}
return convertView;
}
private int calculateRowCount (String key, ExpandableListView listView) {
int groupCount = listDataChild.get(key).size();
int rowCtr = 0;
for(int i = 0; i < groupCount; i++) {
rowCtr++;
if( (listView != null) && (listView.isGroupExpanded(i)))
rowCtr += listDataChild.get(listDataChild.get(key).get(i)).size() - 1;
}
return rowCtr;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
CustomExpandableListView :
public class CustomExpandableListView extends ExpandableListView {
private static final int HEIGHT = 20;
private int rows;
public void setRows(int rows) {
this.rows = rows;
}
public CustomExpandableListView(Context context) {
super(context);
}
public CustomExpandableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(500, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// setMeasuredDimension(getMeasuredWidth(), rows * HEIGHT);
}
}
What I want to do is,when I expand the view, I want all children to be shown and I could just scroll down the ListView. Right now some children are hidden under different children.
Thanks in Advance for your Help.
#Code Word I'm sorry, I forgot to share my solution.
As I mentioned before I implemented treeView with ListView. Here is my source code.
TreeElementI.java :
public interface TreeElementI extends Serializable{
public void addChild(TreeElementI child);
public String getId();
public void setId(String id);
public String getOutlineTitle();
public void setOutlineTitle(String outlineTitle);
public boolean isHasParent();
public void setHasParent(boolean hasParent);
public boolean isHasChild();
public void setHasChild(boolean hasChild);
public int getLevel();
public void setLevel(int level);
public boolean isExpanded();
public void setExpanded(boolean expanded);
public ArrayList<TreeElementI> getChildList();
public TreeElementI getParent();
public void setParent(TreeElementI parent);
}
TreeElement.java :
public class TreeElement implements TreeElementI{
private String id;
private String outlineTitle;
private boolean hasParent;
private boolean hasChild;
private TreeElementI parent;
private int level;
private ArrayList<TreeElementI> childList;
private boolean expanded;
public TreeElement(String id, String outlineTitle) {
super();
this.childList = new ArrayList<TreeElementI>();
this.id = id;
this.outlineTitle = outlineTitle;
this.level = 0;
this.hasParent = true;
this.hasChild = false;
this.parent = null;
}
public TreeElement(String id, String outlineTitle, boolean hasParent, boolean hasChild, TreeElement parent, int level, boolean expanded) {
super();
this.childList = new ArrayList<TreeElementI>();
this.id = id;
this.outlineTitle = outlineTitle;
this.hasParent = hasParent;
this.hasChild = hasChild;
this.parent = parent;
if(parent != null) {
this.parent.getChildList().add(this);
}
this.level = level;
this.expanded = expanded;
}
#Override
public void addChild(TreeElementI child) {
this.getChildList().add(child);
this.setHasParent(false);
this.setHasChild(true);
child.setParent(this);
child.setLevel(this.getLevel() + 1);
}
#Override
public String getId() {
return this.id;
}
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getOutlineTitle() {
return this.outlineTitle;
}
#Override
public void setOutlineTitle(String outlineTitle) {
this.outlineTitle = outlineTitle;
}
#Override
public boolean isHasParent() {
return this.hasParent;
}
#Override
public void setHasParent(boolean hasParent) {
this.hasParent = hasParent;
}
#Override
public boolean isHasChild() {
return this.hasChild;
}
#Override
public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}
#Override
public int getLevel() {
return this.level;
}
#Override
public void setLevel(int level) {
this.level = level;
}
#Override
public boolean isExpanded() {
return this.expanded;
}
#Override
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
#Override
public ArrayList<TreeElementI> getChildList() {
return this.childList;
}
#Override
public TreeElementI getParent() {
return this.parent;
}
#Override
public void setParent(TreeElementI parent) {
this.parent = parent;
}
}
TreeViewClassifAdapter.java :
public class TreeViewClassifAdapter extends BaseAdapter {
private static final int TREE_ELEMENT_PADDING_VAL = 25;
private List<TreeElementI> fileList;
private Context context;
private Bitmap iconCollapse;
private Bitmap iconExpand;
private Dialog dialog;
private EditText textLabel;
private XTreeViewClassif treeView;
public TreeViewClassifAdapter(Context context, List<TreeElementI> fileList, Dialog dialog, EditText textLabel, XTreeViewClassif treeView) {
this.context = context;
this.fileList = fileList;
this.dialog = dialog;
this.textLabel = textLabel;
this.treeView = treeView;
iconCollapse = BitmapFactory.decodeResource(context.getResources(), R.drawable.x_treeview_outline_list_collapse);
iconExpand = BitmapFactory.decodeResource(context.getResources(), R.drawable.x_treeview_outline_list_expand);
}
public List<TreeElementI> getListData() {
return this.fileList;
}
#Override
public int getCount() {
return this.fileList.size();
}
#Override
public Object getItem(int position) {
return this.fileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
convertView = View.inflate(context, R.layout.x_treeview_classif_list_item, null);
holder = new ViewHolder();
holder.setTextView((TextView) convertView.findViewById(R.id.text));
holder.setImageView((ImageView) convertView.findViewById(R.id.icon));
convertView.setTag(holder);
final TreeElementI elem = (TreeElementI) getItem(position);
int level = elem.getLevel();
holder.getIcon().setPadding(TREE_ELEMENT_PADDING_VAL * (level + 1), holder.icon.getPaddingTop(), 0, holder.icon.getPaddingBottom());
holder.getText().setText(elem.getOutlineTitle());
if (elem.isHasChild() && (elem.isExpanded() == false)) {
holder.getIcon().setImageBitmap(iconCollapse);
} else if (elem.isHasChild() && (elem.isExpanded() == true)) {
holder.getIcon().setImageBitmap(iconExpand);
} else if (!elem.isHasChild()) {
holder.getIcon().setImageBitmap(iconCollapse);
holder.getIcon().setVisibility(View.INVISIBLE);
}
IconClickListener iconListener = new IconClickListener(this, position);
TextClickListener txtListener = new TextClickListener((ArrayList<TreeElementI>) this.getListData(), position);
holder.getIcon().setOnClickListener(iconListener);
holder.getText().setOnClickListener(txtListener);
return convertView;
}
private class ViewHolder {
ImageView icon;
TextView text;
public TextView getText() {
return this.text;
}
public void setTextView(TextView text) {
this.text = text;
}
public ImageView getIcon() {
return this.icon;
}
public void setImageView(ImageView icon) {
this.icon = icon;
}
}
/**
* Listener For TreeElement Text Click
*/
private class TextClickListener implements View.OnClickListener {
private ArrayList<TreeElementI> list;
private int position;
public TextClickListener(ArrayList<TreeElementI> list, int position) {
this.list = list;
this.position = position;
}
#Override
public void onClick(View v) {
treeView.setXValue(String.valueOf(list.get(position).getId()));
dialog.dismiss();
}
}
/**
* Listener for TreeElement "Expand" button Click
*/
private class IconClickListener implements View.OnClickListener {
private ArrayList<TreeElementI> list;
private TreeViewClassifAdapter adapter;
private int position;
public IconClickListener(TreeViewClassifAdapter adapter, int position) {
this.list = (ArrayList<TreeElementI>) adapter.getListData();
this.adapter = adapter;
this.position = position;
}
#Override
public void onClick(View v) {
if (!list.get(position).isHasChild()) {
return;
}
if (list.get(position).isExpanded()) {
list.get(position).setExpanded(false);
TreeElementI element = list.get(position);
ArrayList<TreeElementI> temp = new ArrayList<TreeElementI>();
for (int i = position + 1; i < list.size(); i++) {
if (element.getLevel() >= list.get(i).getLevel()) {
break;
}
temp.add(list.get(i));
}
list.removeAll(temp);
adapter.notifyDataSetChanged();
} else {
TreeElementI obj = list.get(position);
obj.setExpanded(true);
int level = obj.getLevel();
int nextLevel = level + 1;
for (TreeElementI element : obj.getChildList()) {
element.setLevel(nextLevel);
element.setExpanded(false);
list.add(position + 1, element);
}
adapter.notifyDataSetChanged();
}
}
}
}
I hope it's not too late and this source code will help you.