Selection of all check boxes in listview - android

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

Related

How to store the position of the items in list view with checkbox checked into the bundle?

I have a listview and each row I have a checkbox. I have a button to show the items in listview being selected when it is clicked. My problem is that when orientation changes, all the selection will be gone. I know I need to store the position of items in the listview with the checkbox checked into the bundle but I do not know how to do it. Can someone help me?
Here is my main activity.
public class MainActivity extends AppCompatActivity {
ListView mainActivity;
// creating arraylist of MyItem type to set to adapter
ArrayList<MyItem> myItems = new ArrayList<>();
Button button;
MyCustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = (ListView) findViewById(R.id.mainactivitylistview);
myItems.add(new MyItem("Greece", "Athens",R.drawable.amsterdam_icon,false));
myItems.add(new MyItem("Emirate of Dubai","Dubai",R.drawable.dubai_icon,false));
myItems.add(new MyItem("Netherlands","Amsterdam",R.drawable.amsterdam_icon,false));
myItems.add(new MyItem("England","London",R.drawable.london_icon,false));
myItems.add(new MyItem("Egypt","Giza",R.drawable.egypt_icon,false));
myItems.add(new MyItem("France","Paris",R.drawable.paris_icon,false));
myItems.add(new MyItem("Russia","Moscow",R.drawable.moscow_icon,false));
myItems.add(new MyItem("Italy","Florence",R.drawable.florence_icon,false));
myItems.add(new MyItem("Switzerland","Zurich",R.drawable.zurich_icon,false));
myItems.add(new MyItem("Japan","Tokyo",R.drawable.tokyo_icon,false));
//Creating Adapter object for setting to list
adapter = new MyCustomAdapter(myItems, MainActivity.this);
mainActivity.setAdapter(adapter);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Your Wishlist");
builder.setMessage(adapter.getWishlist().toString().replace("[","").replace("]","").replace(",",""));
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}}
Here is my adapter.
public class MyCustomAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<MyItem> myList= new ArrayList<>();
private ArrayList<String> wishList = new ArrayList<>();
private ArrayList<Integer> positionList = new ArrayList<>();
public MyCustomAdapter(ArrayList<MyItem> itemArray,Context mContext) {
super();
this.mContext = mContext;
myList=itemArray;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public String getItem(int position) {
return myList.get(position).toString();
}
#Override
public long getItemId(int position) {
return position;
}
public ArrayList<String> getWishlist() {
return wishList;
}
public ArrayList<Integer> getPositionList() {
return positionList;
}
public class ViewHolder {
public TextView name_country;
public TextView name_city;
public CheckBox checkBox;
public ImageView imageView;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view = null;
LayoutInflater inflator = ((Activity) mContext).getLayoutInflater();
if (view == null) {
view = new ViewHolder();
convertView = inflator.inflate( R.layout.myadapter, null);
view.name_city = (TextView) convertView.findViewById(R.id.name_city);
view.name_country=(TextView) convertView.findViewById(R.id.name_country);
view.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
view.imageView = (ImageView) convertView.findViewById(R.id.imageView);
view.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here
// we get the position that we have set for the checkbox using setTag.
myList.get(getPosition).setChecked(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
if (isChecked) {
wishList.add(myList.get(position).getName_city() + "\n");
positionList.add(position);
}
else
{
wishList.remove(myList.get(position).getName_city() + "\n");
positionList.remove(position);
}
}
});
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.imageView.setImageResource(myList.get(position).getImgId());
view.checkBox.setTag(position);
view.name_country.setText(myList.get(position).getName_country());
view.name_city.setText(myList.get(position).getName_city());
view.checkBox.setChecked(myList.get(position).isChecked());
return convertView;
}}
Here is MyItem.java.
public class MyItem {
private String name_country;
private String name_city;
private int ImgId;
private boolean checked;
public MyItem(String name_country, String name_city, int imgId, boolean checked) {
this.name_country = name_country;
this.name_city = name_city;
ImgId = imgId;
this.checked = checked;
}
public String getName_country() {
return name_country;
}
public void setName_country(String name_country) {
this.name_country = name_country;
}
public String getName_city() {
return name_city;
}
public void setName_city(String name_city) {
this.name_city = name_city;
}
public int getImgId() {
return ImgId;
}
public void setImgId(int imgId) {
ImgId = imgId;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}}

how to remove custom listview item in 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
}
}
});
}
}

Custom ListView - Duplicate Entries

Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(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)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
}
Activity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
// _adapter = new PersonAdapter(this, _data);
// _listView.setAdapter(_adapter);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object

How to select two list items at same time ? To be specific ONLY TWO items not more than that

I have a list view like the below image.
Now I want to select Only Any two items from the list view at a time and pass the values of both listview items with Intent to next activity. How can I achieve it.?
If Both items are not selected set validation on it?
AdapterClass
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#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
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
Main Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
#Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
#Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
#Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
#Override
public void onListChanged() {
}
#Override
public void onMove(int position, float x) {
}
#Override
public void onStartOpen(int position, int action, boolean right) {
}
#Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
#Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
#Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
#Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList$1.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I would use Action Mode with MultiChoiceModeListener.
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
There is a callback onItemCheckedStateChanged(ActionMode mode, int position, boolean checked).
You can easily get values of already checked list items ListView.getCheckedItemPositions. So you can prevent selection, if you already selected two or even at once pass the values(or ids) of selected ones without any effort.
You can simply put a counter on item selection.
Take a variable say for ex.
int count = 0;
Check this variable before marking item as selected/deselected:
if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
This will make you select ONLY TWO items at a time.
Modify your adapter like this:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#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
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in
adapter and call it with an adapter object like : adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
Answer to issue 2 : If you want to use ImageView instead of text color change. The do the same things as above but replace the TextView + Color with ImageView + Image.
EDIT 3:
You have called the getSelected() method from a Null object. Modify your code like this:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}

custom listview edit value

i have EditText in second activity.so the value enter here will be added to the custom listview in first activity.
i first activity in list i have textview,checkbox and button(edit). here textview will be from second activity edittext data. so here if i click on edit then it navigates to second activity of that particular data .am getting all these now .. in second acitity i want to edit the textfield value .so it has to display the edited value with this data in listview of particular row.
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
String cardNumberData=null;
}
public class Second extends Activity{
EditText cardNumber;
String cardNumberReceived;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.editcredit);
cardNumberReceived = getIntent().getStringExtra("cardwithoutstring");
System.out.println("cardWithOutStringReceived"+cardNumberReceived);
app = ((MyApplication) getApplicationContext());
cardNumber =(EditText)findViewById(R.id.cardnumber);
cardNumber.setText(cardNumberReceived);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.cardNumberData =cardNumber.getText().toString();
System.out.println("Gotcardname"+app.cardNumberData);
app.arryList.add(app.cardNumberData);
System.out.println("Array List Size "+app.arryList.size());
System.out.println("Array List Size "+app.cardTypeList.size());
Intent saveIntent =new Intent(Second.this,First.class);
startActivity(saveIntent);
}
});
}
}
public class First extends Activity{
protected ListItemsState[] mDeletedItemsStates;
protected ArrayAdapter<ListItemsState> mListAdapter;
protected ListView mFoldersListView;
protected Context mContext;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
mDeletedItemsStates = (ListItemsState[])getLastNonConfigurationInstance();
if (mDeletedItemsStates == null) {
mDeletedItemsStates = new ListItemsState[app.arryList.size()];
for (int i = 0; i < app.arryList.size(); i++) {
mDeletedItemsStates[i] = new ListItemsState(app.arryList.get(i),i);
}
}
ArrayList<ListItemsState> gridItemsList = new ArrayList<ListItemsState>();
gridItemsList.addAll(Arrays.asList(mDeletedItemsStates));
mListAdapter = new DeletedItemsStateArrayAdapter(this, gridItemsList);
mFoldersListView.setAdapter(mListAdapter);
mFoldersListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mFoldersListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "am thelist",
Toast.LENGTH_LONG).show();
}
});
}
private static class ListItemsState {
private String produ = "";
private boolean checked = false;
private int position;
public ListItemsState(String produ, int position) {
this.position = position;
}
public String getProdu() {
return produ;
}
public int getPosition() {
return position;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
/** Holds child views for one row. */
private static class ListItemsStateViewHolder {
private RadioButton checkBox;
private TextView produ;
private Button edit;
public TextView getProdu() {
return produ;
}
public Button getEdit() {
return edit;
}
public RadioButton getCheckBox() {
return checkBox;
}
}
private class DeletedItemsStateArrayAdapter extends
ArrayAdapter<ListItemsState> {
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private LayoutInflater inflater;
public DeletedItemsStateArrayAdapter(Context context,
List<ListItemsState> sentItemsStateList) {
super(context, R.layout.customlist, R.id.card,
sentItemsStateList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ListItemsState deletedItemsState = (ListItemsState) this
.getItem(position);
ListItemsStateViewHolder viewHolder = new ListItemsStateViewHolder();
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.customlist, null);
convertView.setTag(new ListItemsStateViewHolder());
}
else {
viewHolder = (ListItemsStateViewHolder) convertView.getTag();
viewHolder.checkBox = viewHolder.getCheckBox();
viewHolder.produ = viewHolder.getProdu();
viewHolder.edit = viewHolder.getEdit();
}
viewHolder.produ = (TextView) convertView.findViewById(R.id.card);
viewHolder.checkBox = (RadioButton) convertView.findViewById(R.id.radioButton1);
viewHolder.edit=(Button)convertView.findViewById(R.id.editbutton);
try {
viewHolder.checkBox.setTag(deletedItemsState);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
viewHolder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent edit =new Intent(getApplicationContext(), Second.class);
edit.putExtra("cardNumberSending",app.arryList.get(position));
edit.putExtra("Indexvalue",mFoldersListView.getItemIdAtPosition(position));
System.out.println("Index value ::::::::: "+mFoldersListView.getItemIdAtPosition(position));
startActivity(edit);
}
});
viewHolder.produ.setText(deletedItemsState.getProdu());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return mDeletedItemsStates;
}
}
You are adding the edited data to the ArrayList Again avoid it inside the Second Activity
app.cardNumberData = cardNumber.getText().toString();
if(arryList.indexOf(cardNumberReceived) != -1)
{
app.arryList.set(arryList.indexOf(cardNumberReceived), app.cardNumberData);
}else
{
app.arryList.add(app.cardNumberData);
}
In your second Activity do this onClick of save.

Categories

Resources