how to remove custom listview item in android - android

i want to remove listview item in my list.. But When I click On Button nothing happened. please tell ME Where I m Doing Wrong...this code can add item but only remove item cant...
//listview java
public class MemberActivity extends AppCompatActivity implements BaseColumns {
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member);
final ListView listview;
final ListViewAdapter adapter;
//final ArrayList<String> items = new ArrayList<String>();
mylist = (ListView) findViewById(R.id.listview1);
final LinearLayout linewarLayout1 = (LinearLayout) findViewById(R.id.addmember);
final LinearLayout linewarLayout2 = (LinearLayout) findViewById(R.id.buttongroup);
adapter = new ListViewAdapter();
listview = (ListView) findViewById(R.id.listview1);
final View header = getLayoutInflater().inflate(R.layout.listview_header, null, false);
listview.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mylist.setVisibility(View.INVISIBLE);
linewarLayout2.setVisibility(View.INVISIBLE);
linewarLayout1.setVisibility(View.VISIBLE);
}
});
final EditText name = ((EditText) findViewById(R.id.etName));
final EditText ID = ((EditText) findViewById(R.id.etID));
final EditText Major = ((EditText) findViewById(R.id.etMajor));
Button btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//TextView cnttxt = (TextView)findViewById(R.id.count);
//cnttxt.setText(adapter.getCount());
adapter.addItem(name.getText().toString(), ID.getText().toString(), Major.getText().toString());
name.setText("");
ID.setText("");
Major.setText("");
Toast.makeText(getApplicationContext(), "add.", Toast.LENGTH_LONG).show();
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
name.setText("");
ID.setText("");
Major.setText("");
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
// delete button
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int count, checked;
count = adapter.getCount();
if (count > 0) {
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
checked = listview.getCheckedItemPosition();
if (checked > -1 && checked < count) {
adapter.removeitem(checked);
listview.clearChoices();
adapter.notifyDataSetChanged();
}
}
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
// get item
ListViewItem item = (ListViewItem) parent.getItemAtPosition(position);
String nameStr = item.getname();
String IDStr = item.getID();
String majorStr = item.getmajor();
}
});
}
}//adapter
public class ListViewAdapter extends BaseAdapter {
private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
public ListViewAdapter() {
}
#Override
public int getCount() {
return listViewItemList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_item, parent, false);
}
TextView nameTextView = (TextView) convertView.findViewById(R.id.list_name);
TextView IDTextView = (TextView) convertView.findViewById(R.id.list_ID);
TextView majorTextView = (TextView) convertView.findViewById(R.id.list_major);
ListViewItem listViewItem = listViewItemList.get(position);
nameTextView.setText(listViewItem.getname());
IDTextView.setText(listViewItem.getID());
majorTextView.setText(listViewItem.getmajor());
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
public void removeitem(int position) {
listViewItemList.remove(position);
notifyDataSetChanged();
}
public void addItem(String name, String ID, String major) {
ListViewItem item = new ListViewItem();
item.setname(name);
item.setID(ID);
item.setmajor(major);
listViewItemList.add(item);
notifyDataSetChanged();
}
}
//ListViewItem java
public class ListViewItem {
private String nameStr;
private String IDStr;
private String majorStr;
public void setname(String name) {
nameStr = name;
}
public void setID(String ID) {
IDStr = ID;
}
public void setmajor(String major) {
majorStr = major;
}
public String getname() {
return this.nameStr;
}
public String getID() {
return this.IDStr;
}
public String getmajor() {
return this.majorStr;
}
}

Update your code as below. Set choice mode to CHOICE_MODE_SINGLE when you crate listview and before set adapter. Remove CHOICE_MODE_SINGLE from button click.
listview = (ListView) findViewById(R.id.listview1);
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setAdapter(adapter);
Also, You need to setItemChecked in onItemClick of listview.
Check below example code.
public class MainActivity extends Activity {
private ListView mListView;
private String[] mData = new String[] { "xxx", "yyy", "zzz", "aaa" };
private BaseAdapter mAdapter;
private int mLastCorrectPosition = -1;
private int mButtonPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, mData);
mListView.setAdapter(mAdapter);
mListView.setSelector(new ColorDrawable(0));
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == mButtonPosition) {
if (mLastCorrectPosition != -1) {
mListView.setItemChecked(mLastCorrectPosition, true);
}
else {
mListView.setItemChecked(mButtonPosition, false);
}
// here show dialog
}
else {
mLastCorrectPosition = position;
// here refresh fragment
}
}
});
}
}

Related

ListView click show/hide all check box

I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});

how to send all the data of array list to another activity?

Daily Screen :-
public class DailyScreen extends AppCompatActivity implements AdapterView.OnItemClickListener {
ImageView add, edit;
MyCustomAdapter adapter1;
Button ok;
Button next2;
final Context context = this;
ListView listView;
private ArrayAdapter<String> adapter;
List<Milk> items=new ArrayList();
public List<Milk> getItems() {
return items;
}
public void setItems(List<Milk> items) {
this.items = items;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_listview);
add = (ImageView) findViewById(R.id.add);
edit = (ImageView) findViewById(R.id.edit);
listView = (ListView) findViewById(R.id.list);
next2 = (Button) findViewById(R.id.next2);
Milk milkDefault=new Milk("Toned Milk",0);
items.add(milkDefault);
//this.setArrayList((ArrayList<String>) Arrays.asList(items));
adapter1 = new MyCustomAdapter(items, this);
listView.setAdapter(adapter1);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);// to set context menu in list view
}
#Override
protected void onResume() {
super.onResume();
next2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DailyScreen.this, SupplierActivity.class);
intent.putExtra("LIST_ITEMS",List,items);//
startActivity(intent);
}
});
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(DailyScreen.this);
dialog.setTitle("Enter new Milk");
dialog.setContentView(R.layout.dialog_box);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
final EditText editText = (EditText) dialog.findViewById(R.id.pro);
String data = editText.getText().toString();
//button initialization
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = editText.getText().toString();
if (!data.isEmpty()) {
items.add(new Milk(data,0));
adapter1.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "product name is :" + data, Toast.LENGTH_LONG).show();
dialog.cancel();
}
else{
Toast.makeText(DailyScreen.this, "Please enter the data", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
MyCustomAdapter class
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private List<Milk> list = new ArrayList<Milk>();
private Context context;
public MyCustomAdapter(List<Milk> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_layout, null);
}
TextView name = (TextView) view.findViewById(R.id.text);
name.setText(list.get(position).getNsme());
final TextView milkCount = (TextView) view.findViewById(R.id.milkcount);
milkCount.setText(""+list.get(position).getAmount());
ImageView increment = (ImageView) view.findViewById(R.id.add);
ImageView decrement = (ImageView) view.findViewById(R.id.sub_item);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
a = a + 1;
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
if (a == 0) {
a = 0;
} else {
a = a - 1;
}
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
return view;
}
Milk class
public class Milk {
private String nsme ;
private int amount ;
public Milk(String nsme, int amount) {
this.nsme = nsme;
this.amount = amount;
}
public String getNsme() {
return nsme;
}
public void setNsme(String nsme) {
this.nsme = nsme;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
i have tried all thing to send all the data of list view to another activty please suggest me how can i do it ??
Make the list static and u can then access it in any activity. Make sure u initialise the list
milk class extends serializable firstly
then u do
make object of milk class in mainactivity class
Milk milk=new Milk(this);
Intent i=new Intent(getApplicationContext(),Update.class);
i.putExtra("emnumber",(Serializable)milk);
startActivity(i);
then u can pick the value in update class
if(getIntent().getSerializableExtra("emnumber")!=null) {
con = (ArrayList<Contact>) getIntent().getSerializableExtra("emnumber");
email_mobile = contactList.get(0).nsme;
pass__word = contactList.get(0).amount;
you can implement as:
public class Milk implements Parcelable{
......
}
Send arraylist as:
intent.putExtra("files", "your arraylist");
obtain arraylist as:
Intent inIntent = getIntent();
list=inIntent.getParcelableArrayListExtra("files");
Try this. May be it help.
Send arraylist to activity through extras.
intent.putStringArrayListExtra("ARRAY_LIST", arrayList);
Retrieve arraylist in activity.
arrayList= i.getStringArrayListExtra("ARRAY_LIST");
If u have to send arraylist other than string then.
intent.putParcelableArrayListExtra("ARRAY_LIST", (ArrayList<Milk>) milkArrayList);
Milk class must be parcellable

how to set value list item in adapter class and get value on Button click in android

Adapter Class:
public List<TSPDataModel> employeeData;
private Context mContext;
private LayoutInflater mInflater;
RadioGroup radiogroupbutton;
String[] data = {"Document not clear","Adress is not Visibile","Photo is not pasted","Signature is not Avilable"};
String value;
public TSPListDocumentadapter(Context context, int textViewResourceId,
List<TSPDataModel> objects)
{
this.employeeData = objects;
this.mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.tspdocumentlistitem, null);
holder.relatvie1=(RelativeLayout)convertView.findViewById(R.id.relatvie1);
holder.txtName = (TextView) convertView.findViewById(R.id.textView1);
holder.accecpt = (ImageView) convertView.findViewById(R.id.imageButton);
holder.reject = (ImageView) convertView.findViewById(R.id.imageButton2);
holder.statustextview = (TextView) convertView.findViewById(R.id.statustextview);
holder.poaedittext=(TextView) convertView.findViewById(R.id.poieditext);
holder.poaedittext=(TextView)convertView.findViewById(R.id.poaedittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(employeeData.get(position).getName());
holder.poaedittext.setText(employeeData.get(position).getPoa());
holder.accecpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.statustextview.setText("Accepted");
employeeData.get(position).setSelected(true);
employeeData.get(position).getOrderId();
holder.relatvie1.setBackgroundResource(R.color.acceptedcolor);
}
});
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog();
holder.statustextview.setText("Rejected");
employeeData.get(position).setSelected(false);
employeeData.get(position).setReasone(value);
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
return convertView;
}
static class ViewHolder {
TextView txtName;
ImageView reject;
ImageView accecpt;
TextView statustextview;
TextView poiedittext;
TextView poaedittext;
RelativeLayout relatvie1;
}
public int getCount() {
return employeeData.size();
}
public TSPDataModel getItem(int position) {
return employeeData.get(position);
}
public long getItemId(int position) {
return 0;
}
public void showdilog() {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
This Button click in my actvity class :
#Override
public void onClick(View view) {
if (view.getId() == R.id.button1) {
try {
List<TSPDataModel> empData = adapter.employeeData;
System.out.println("Total Size :" + empData.size());
for (TSPDataModel employeeModel : empData) {
if (employeeModel.isSelected()) {
Toast.makeText(TSPDocumentListActvity.this, employeeModel.getName(), Toast.LENGTH_LONG).show();
} else {
String Reasonse= employeeModel.getresonse() ;
Toast.makeText(TSPDocumentListActvity.this, "false" + employeeModel.getName(), Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
First i Print data in Listview then each list view item there is accept and reject Button is there when we click on accept then no alert will asked only reject button reason will ask which is come on listitem on popup i want to get that selected reason on Button click in actvity but i always get null value please help me where i am doing wrong
change your reject button and showDialog code to
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog(position);
holder.statustextview.setText("Rejected");
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
and showDualog to
public void showdilog(int list_position) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
employeeData.get(list_position).setSelected(false);
employeeData.get(list_position).setReasone(value);
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}

How to refresh ListView custom adapter data from the event listener that is in the adapter in Android?

I am a beginner to Android. Now I am working with ListView using custom adapter and custom view. Custom adapter is created as into a separate file. But inside my custom adapter, I set up a click listener for a button of the layout of the list view row. But my problem is how can I update items of the adapter inside event listener that is created inside the custom adapter.
This is my Listview Fragment:
public class TaskListFragment extends Fragment {
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
}
Inside the fragment, when I click the done button listView adapter is updated properly and it is working find. Done button is inside the AlertDialog box that appear when long click on one of the rows of list view.
The problem is here.
This is my custom adapter class:
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
So how can I update the listview items and listview from the click event listener of done button that is inside custom adapter class.
public class TaskListFragment extends Fragment implements TaskListAdapter.RefreshAdapter{//change
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
adapter.setRefreshAdapter(this);//change
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
//change
#Override
public void OnlickRefreshAdapter(){
//todo your code here
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
}
}
adapter class
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
private RefreshAdapter refreshAdapter;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
public Interface RefreshAdapter{
public void OnlickRefreshAdapter();
}
public setRefreshAdapter(RefreshAdapter refresh){
refreshAdapter = refresh;
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
I got the answer, actually it is too simple. What I need to do is just add this code inside the click listener of done button in the custom adapter.
This is the click listener of the doneBtn in custom adapter:
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
if(values!=null)
{
Task oldTask = values.get(position);
oldTask.setDone(Boolean.TRUE);
values.set(position,oldTask);
notifyDataSetChanged();
}
}
});

Selection of all check boxes in listview

I want to select all check boxes in a listview but I'm not able to get checkbox objects from the listview. I can select a single check box but not multiple check boxes.
Your suggestion are appreciable.
Code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bir);
mainListView = (ListView) findViewById(R.id.mainListView);
selectall = (Button) findViewById(R.id.button1);
selectall.setOnClickListener(this);
save = (Button) findViewById(R.id.button2);
save.setOnClickListener(this);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
}
});
}
}
class Amphian:
private static class Amphian
{
private String name = "" ;
private boolean checked = false ;
public Amphian( String name )
{
this.name = name ;
}
public Amphian( String name, boolean checked )
{
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
#Override
public String toString() {
return name ;
}
public void toggleChecked()
{
checked = !checked ;
}
}
class AmphiansArrayAdapter:
public class AmphiansArrayAdapter extends ArrayAdapter<Amphian>
{
Integer name[] =
{
R.raw.ducks_landing_in_water,
R.raw.flicker_chicks_feeding,
R.raw.geese_honking_loud,
R.raw.geese_honking_distant,
R.raw.gold_finch,
R.raw.humming_bird_feeding,
R.raw.indigo_bunting,
R.raw.loons,
R.raw.little_blue_heron_fishing,
R.raw.pelican_chick,
R.raw.purple_martins,
R.raw.red_winged_blackbird,
R.raw.shorebirds_close,
R.raw.shorebirds_distant,
R.raw.shorebirds_misc,
R.raw.shoreseabirds,
R.raw.snow_geese_flock,
R.raw.terns,
R.raw.tufted_titmouse,
R.raw.tundra_swans,
R.raw.wood_stork_chicks,
R.raw.woodpecker_tapping
};
private final LayoutInflater inflater;
public AmphiansArrayAdapter(Context context, List<Amphian> amphianList)
{
super( context, R.layout.simplerow, R.id.rowTextView, amphianList );
inflater = LayoutInflater.from(context) ;
}
#Override
public View getView( final int position, View convertView , ViewGroup parent)
{
final Amphian amphian=this.getItem(position);
mp=new MediaPlayer();
if ( convertView == null )
{
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById( R.id.rowTextView );
checkBox = (CheckBox) convertView.findViewById( R.id.checkBox1 );
button = (Button)convertView.findViewById(R.id.button1);
// Optimization: Tag the row with it's child views, so we don't have to
// call findViewById() later when we reuse the row.
convertView.setTag( new AmphianViewHolder(textView,checkBox,button) );
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cb= (CheckBox) v;
Log.e("cb",String.valueOf(cb));
Amphian amphian = (Amphian) cb.getTag();
Log.e("cb",String.valueOf(cb.getTag()));
amphian.setChecked(cb.isChecked());
Log.e("dd", "ddd");
}
});
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Button bu=(Button)v;
Amphian amphian;
//= (Amphian) bu.getTag();
//Log.e(String.valueOf(amphian),"ddd");
Try this.
public class MainActivity extends Activity implements OnClickListener {
public class LVSample3Adapter extends BaseAdapter{
private Context context;
private List<LVSample3Item> itemList;
public LVSample3Adapter(List<LVSample3Item> lstItems,
MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.context=mainActivity;
this.itemList=lstItems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("lstItems1:", String.valueOf(position));
LVSample3Item item = itemList.get(position);
convertView =LayoutInflater.from(context).inflate(R.layout.list, parent, false);
TextView t1=(TextView)convertView.findViewById(R.id.textView1);
t1.setText(item.getTitle());
CheckBox chb1=(CheckBox)convertView.findViewById(R.id.checkBox1);
chb1.setChecked(item.getstate());
return convertView;
}
}
/** Called when the activity is first created. */
private ListView lv;
private ListAdapter adapter;
private Button btn1,btn2;
private List<LVSample3Item> lstItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
lstItems = new ArrayList<LVSample3Item>();
LVSample3Item item = new LVSample3Item("drinks",false);
lstItems.add(item);
item = new LVSample3Item("chat",false);
lstItems.add(item);
item = new LVSample3Item("chat1",true);
lstItems.add(item);
item = new LVSample3Item("chat2",false);
lstItems.add(item);
adapter = new LVSample3Adapter(lstItems, this);
lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.button1){
Log.e("lstItems:", String.valueOf(lstItems.size()));
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(!item.getstate()){
item.setpath(true);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}else if(v.getId()==R.id.button2){
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(item.getstate()){
item.setpath(false);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
public class LVSample3Item implements Serializable {
private String title;
private boolean state;
public LVSample3Item(String title,boolean imagepath) {
this.title = title;
this.state=imagepath;
}
public String getTitle() {
return title;
}
public boolean getstate() {
return state;
}
public void setTitle(String title) {
this.title = title;
}
public void setpath(boolean imagepath) {
this.state = imagepath;
}
}
There is too much code to read, so I give you a sample how to do that:
int count = list.getCount();
for (int i = 0; i < count; i++) {
View child = list.getItemAtPosition(i);
//check that child..
}
or
int count = list.getChildCount();
for (int i = 0; i < count; i++) {
View child = list.getChildAt(i);
//check that child..
}
selectall.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
list.getItem(i).setChecked(true);
}
}
});
try doing soething like this

Categories

Resources