Listview Array Adapter position onClick - android

I have a listview with an ArrayAdapter. The ListView at a position fills itselfs with the same position in some ArrayList. In each listitem
there are two buttons. When the onClickListener start, it gets
the position of the overrided View getView(position, View etc.), takes some variables out of the ArrayList and sends it to a database. The problem is, the position is not really accurate. Sometimes I get the position of a Listitem above the Listitem I want. Here is the code:
public class MemoAdapter extends ArrayAdapter<String> {
private final Activity context;
ArrayList<String> commentarray;
ArrayList<String> fromarray;
ArrayList<String> datearray;
ArrayList<String> ids;
ArrayList<String> feedback;
Dialog dialog;
EditText feedbacktxt;
String token;
String website;
public MemoAdapter(Activity context, ArrayList<String> commentArray,
ArrayList<String> fromArray, ArrayList<String> dateArray,
ArrayList<String> ids, ArrayList<String> feedback, String token,
String website) {
super(context, R.layout.memo_listitem, commentArray);
this.context = context;
this.commentarray = commentArray;
this.fromarray = fromArray;
this.datearray = dateArray;
this.ids = ids;
this.feedback = feedback;
this.token = token;
this.website = website;
}
#Override
public long getItemId(int position) {
return 0;
}
// static to save the reference to the outer class and to avoid access to
// any members of the containing class
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView3;
public TextView textView4;
// public ImageView reply;
// public ImageView accept;
public Button reply;
public Button accept;
public RelativeLayout r;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.memo_listitem, null);
holder = new ViewHolder();
holder.textView = (TextView) rowView
.findViewById(R.id.memodescription);
holder.textView2 = (TextView) rowView.findViewById(R.id.memofrom);
holder.textView3 = (TextView) rowView.findViewById(R.id.memodate);
holder.textView4 = (TextView) rowView
.findViewById(R.id.memofeedback);
holder.reply = (Button) rowView.findViewById(R.id.buttonFeedback);
holder.accept = (Button) rowView.findViewById(R.id.buttonAccepteer);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.textView.setText(commentarray.get(position));
holder.textView2.setText(datearray.get(position));
holder.textView3.setText(fromarray.get(position));
holder.textView4.setText(feedback.get(position));
if (holder.textView4.getText().toString().equals("")
|| holder.textView4.getText().toString().equals(" ")) {
holder.textView4.setText(" - ");
}
// ONCLICKLISTENER FOR REPLYIMAGE
holder.reply.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = new Dialog(NostradamusActivity2.parentcontext);
dialog.setContentView(R.layout.memo_dialog);
dialog.setTitle("Feedback");
feedbacktxt = (EditText) dialog.findViewById(R.id.memoeddittxt);
Button cancel = (Button) dialog
.findViewById(R.id.memobtncancel);
// CANCEL BUTTON ONCLICKLISTENER REPLYIMAGE
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
Button okay = (Button) dialog.findViewById(R.id.memobtnokay);
// OKAY BUTTON ONCLICKLISTENER REPLYIMAGE
okay.setOnClickListener(new OnClickListener() {
private String errormessage;
private AlertDialog alertDialog;
public void onClick(View v) {
Database2 db = new Database2(
"https://"
+ website
+ "/index2.php?option=com_webservices&controller=json&method=core.memos.memo_feedback&token=",
"token", token, "id", ids.get(position),
"memo_feedback", feedbacktxt.getText()
.toString());
}
// //ACCEPTEER MEMO BUTTON ONCLICKLISTENER
holder.accept.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
NostradamusActivity2.parentcontext);
builder.setMessage("Heeft u de opdracht uitgevoerd?")
.setCancelable(false)
.setPositiveButton("Ja",
new DialogInterface.OnClickListener() {
private AlertDialog alertDialog;
public void onClick(DialogInterface dialog,
int id) {
Database2 dbaccept = new Database2(
"http://intern.koeckers.nl/index2.php?option=com_webservices&controller=json&method=core.memos.memo_state&token=",
"token", token, "id", ids
.get(position),
"memo_completed", "1");
dialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Nee",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return rowView;
}
}

You are getting the item by ids.get(position).
You are using the arrayList, instead use the getTag() method.
rowView.getTag() will give you the ViewHolder from which, you can get the correct ids and Feedback Text.
Database2 dbaccept = new Database2(
"http://intern.koeckers.nl/index2.php? option=com_webservices&controller=json&method=core.memos.memo_state&token=",
"token", token, "id", ids.get(position),
"memo_completed", "1");

Related

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();
}

list view repeating values several times and repeating check box selection every after 6th value

I am using a custom list view base adapter. while passing values to the adapter its repeating values. and in viewholder I am using a checkbox, while selecting that checkbox list auto select the every 6th checkbox after that.
here is my adapter full code.
public class CallLogAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater li;
List<CallLogInfo> callData;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Context context;
static Boolean checkboxstate[];
ArrayList<MultipleSelectedContact> mainDataList;
int i = 0;
public CallLogAdapter(Activity activity, List<CallLogInfo> callData, ArrayList<MultipleSelectedContact> selectedContacts) {
this.activity = activity;
this.callData = callData;
this.mainDataList = selectedContacts;
context = activity;
checkboxstate = new Boolean[callData.size()];
}
// View lookup cache
private static class ViewHolder {
TextView phoneNo, date, addComment, duration;
CheckBox checkBox;
CardView card;
ImageView callTypeImage;
int count;
}
#Override
public int getCount() {
if (callData != null && callData.size() != 0) {
return callData.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return callData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder viewHolder; // view lookup cache stored in tag
if (v == null) {
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.single_card, parent, false);
viewHolder = new ViewHolder();
viewHolder.card = (CardView) v.findViewById(R.id.card_view);
viewHolder.callTypeImage = (ImageView) v.findViewById(R.id.callTypeImage);
viewHolder.phoneNo = (TextView) v.findViewById(R.id.phoneNoText);
viewHolder.date = (TextView) v.findViewById(R.id.dateText);
viewHolder.duration = (TextView) v.findViewById(R.id.callDurationText);
viewHolder.checkBox = (CheckBox) v.findViewById(R.id.checkBox);
viewHolder.addComment = (TextView) v.findViewById(R.id.addCommentText);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
viewHolder.count = position;
final CallLogInfo Info;
Info = callData.get(position);
switch (Info.callType) {
case "Outgoing":
viewHolder.callTypeImage.setImageResource(R.mipmap.up_arrow);
break;
case "Incoming":
viewHolder.callTypeImage.setImageResource(R.mipmap.down_arrow);
break;
case "Missed":
viewHolder.callTypeImage.setImageResource(R.mipmap.miss_arrow);
break;
}
viewHolder.phoneNo.setText(Info.phoneNo);
viewHolder.date.setText(Info.date);
viewHolder.duration.setText(Info.duration);
viewHolder.addComment.setTag(viewHolder.count);
viewHolder.checkBox.setTag(viewHolder.count);
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (((CheckBox) view).isChecked()) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = true;
mainDataList.add(i, new MultipleSelectedContact());
mainDataList.get(i).phoneNoS = Info.phoneNo;
mainDataList.get(i).setIsSelected(viewHolder.checkBox.isSelected());
map.put(((int) viewHolder.checkBox.getTag()), i);
i++;
view.setSelected(true);
} else {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
mainDataList.remove(map.get(((int) viewHolder.checkBox.getTag())));
view.setSelected(false);
}
}
});
viewHolder.addComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_add_comment);
dialog.setTitle("Add Comment Here..");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.messageEditText);
Button dialogButton = (Button) dialog.findViewById(R.id.messageAddButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = text.getText().toString();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "CallLogDb", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession session = daoMaster.newSession();
CallCommentsDetailDao callCommentDao = session.getCallCommentsDetailDao();
CallCommentsDetail commentInfo = new CallCommentsDetail();
commentInfo.setCommentId(position);
commentInfo.setComments(comment);
callCommentDao.insertOrReplace(commentInfo);
session.clear();
db.close();
dialog.dismiss();
}
});
dialog.show();
}
});
viewHolder.card.setTag(position);
viewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MessageContentActivity.class);
intent.putExtra("callDetails", Info);
context.startActivity(intent);
}
});
return v;
}
}
Here in the code where I am using ((int) viewHolder.checkBox.getTag()) . I tried using position also. but still its not working..
can anyone please help me to find out where I am going wrong
Set your check box state on getView
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewholder.checkbox.setChecked(checkboxstate[((int)viewHolder.checkBox.getTag())]);
You can use a SparseBooleanArray to save the states of the checkbox instead of setting it as tag and you are not setting the checkbox state in getView() method like
viewholder.checkbox.setChecked(booleanArray.valueAt(position))
then toggle the state on OnClick() something like
booleanArray.put(position,!booleanArray.valueAt(position));
notifyDataSetChanged();
Also listItemClick won't work properly if the list row contains checkboxes or buttons.Use Recyclerview for better customisation and performance.
Sample Implementation of recyclerview

How to make dynamically add or remove edit text in listview

public class SoloPlayActivity extends BaseActivity implements View.OnClickListener{
private ListView case_list;
private RelativeLayout add_case;
private TextView num_case_textview;
private Button start_button;
ArrayList<ItemSoloplayCase> caseArrayList;
AdapterSoloplay adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solo_play);
initView();
//처음에는 경우의 수가 아무것도 없음
num_case_textview.setText("0");
caseArrayList = new ArrayList<ItemSoloplayCase>();
adapter = new AdapterSoloplay(this, caseArrayList, num_case_textview);
case_list.setAdapter(adapter);
}
private void initView(){
add_case = (RelativeLayout)findViewById(R.id.add_case);
add_case.setOnClickListener(this);
num_case_textview = (TextView)findViewById(R.id.num_case);
start_button = (Button)findViewById(R.id.game_start);
start_button.setOnClickListener(this);
case_list = (ListView)findViewById(R.id.case_list);
//리스트뷰에서 포커스를 잃지 않도록 한다.
case_list.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
#Override
protected String getActionbarTitle() {
return getString(R.string.solo_play_name);
}
//뒤로가기가 눌렸을때 추가한 경우의 수가 있을경우에만 다이얼로그 띄우고 경우의수가 비었다면 그냥 종료
#Override
public void onBackPressed() {
if (!caseArrayList.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("입력한 경우의 수는 모두 사라집니다. 정말로 닫겠습니까?")
.setCancelable(false)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SoloPlayActivity.this.finish();
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
SoloPlayActivity.this.finish();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.game_start:
Toast.makeText(getApplicationContext(), "게임시작 버튼 누름", Toast.LENGTH_SHORT);
break;
case R.id.add_case:
//경우의수 추가
ItemSoloplayCase additem = new ItemSoloplayCase();
caseArrayList.add(additem);
num_case_textview.setText(Integer.toString(caseArrayList.size()));
adapter.notifyDataSetChanged();
break;
}
}}
activity file.
Adapter file.
public class AdapterSoloplay extends BaseAdapter {
private Context context;
private ArrayList<ItemSoloplayCase> caselist;
private TextView num_case;
//순서 갱신 오류, 해당 지운 에디트가 지워지지 않음
public AdapterSoloplay(Context context, ArrayList<ItemSoloplayCase> caselist, TextView num_case) {
this.context = context;
this.caselist = caselist;
this.num_case = num_case;
}
#Override
public int getCount() {
return caselist.size();
}
#Override
public Object getItem(int position) {
return caselist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Viewholder holder;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_case_input, parent, false);
holder = new Viewholder();
holder.order = (TextView) convertView.findViewById(R.id.order_num);
holder.editText = (EditText)convertView.findViewById(R.id.input_case);
holder.button_clear = (ImageButton)convertView.findViewById(R.id.remove_case);
//순서는 현재 크기만큼
holder.order.setText(Integer.toString(getCount()));
convertView.setTag(holder);
}
else
holder = (Viewholder)convertView.getTag();
//클리어를 눌럿을때 제거하고 순서를 재정렬하고 갱신시킨다
holder.button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemSoloplayCase item = (ItemSoloplayCase)getItem(position);
item = null;
caselist.remove(position);
notifyDataSetChanged();
num_case.setText(Integer.toString(caselist.size()));
}
});
return convertView;
}
class Viewholder {
private EditText editText;
private TextView order;
private ImageButton button_clear;
}
}
i want to make dynamically add or remove edit text in list view. '
like image.
enter image description here
if i want remove second list(in this image, b) but it removed last data(in this image, d). and i click add button it makes last data..(in this image, makes edit text value d).
above is my code. help.
please help me.
Add a linearlayout to listview rows xml file :
For add dynamically EditText to this layout try this :
EditText editText = new EditText(context);
editText.setHint(hint);
editText.requestFocus();
editText.setSelection(editText.getText().length());
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
linearlayout.addview(editText);

Listview item button triggering other listview items on scroll with custom CursorAdapter

Perhaps i'm confused about the difference between BindView and getView, but both of them cause the same problem. I have a button on every listview item that when pressed is supposed to show an ImageView beneath it when pressed.
Ive been trying to figure this out for almost a week now, and what ive come to learn is that it has something to do with Recycling views upon scrolling and that getView was supposed to remedy that. However it made it worse in that not only was it still displaying the image on items beneath it, but it was also displaying the wrong image on the one i pressed.
Im totally lost here. =(
This is my Cursor Adapter:
public class ItemAdapter extends CursorAdapter {
private LayoutInflater mLayoutInflater;
private Context mContext;
ListView listView;
Bitmap myBitmap;
ImageView myImage;
Cursor cursor;
public ItemAdapter(Context context, Cursor c) {
super(context, c);
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(R.layout.item_layout, parent, false);
return v;
}
#Override
public void bindView(final View v, Context context, Cursor c) {
final DBAdapter dbAdapter = new DBAdapter(mContext);
listView = (ListView) v.findViewById(R.id.listViewFromDB);
final String description = c.getString(c.getColumnIndexOrThrow(DBAdapter.DBHelper.DESCRIPTION));
final String detail = c.getString(c.getColumnIndexOrThrow(DBAdapter.DBHelper.DETAIL));
final String importance = c.getString(c.getColumnIndexOrThrow(DBAdapter.DBHelper.IMPORTANCE));
final String id = c.getString((c.getColumnIndexOrThrow(DBAdapter.DBHelper.UID)));
final ImageButton trash = (ImageButton) v.findViewById(R.id.trash);
final ImageButton edit = (ImageButton) v.findViewById(R.id.editButton);
ImageButton expandButton = (ImageButton) v.findViewById(R.id.expand);
final ImageView drawnImage = (ImageView) v.findViewById(R.id.drawnImage);
final TextView idFlag = (TextView) v.findViewById(R.id.idFlag);
final File imgFile = new File("/data/data/com.eboodnero.memoir/files/" + id + ".png");
expandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (trash.getVisibility() == View.INVISIBLE && id == idFlag.getText().toString()) {
trash.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
myImage = (ImageView) v.findViewById(R.id.drawnImage);
drawnImage.setVisibility(View.VISIBLE);
myImage.setImageBitmap(myBitmap);
myImage.setMaxWidth(50);
myImage.setMaxHeight(50);
}
} else if (trash.getVisibility() == View.VISIBLE) {
drawnImage.setVisibility(View.GONE);
trash.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
});
TextView descriptionText = (TextView) v.findViewById(R.id.description);
Typeface helveticaLight = Typeface.createFromAsset(mContext.getAssets(), "fonts/HelveticaNeue-Light.ttf");
descriptionText.setTypeface(helveticaLight);
if (descriptionText != null) {
descriptionText.setText(description);
}
TextView detailText = (TextView) v.findViewById(R.id.detail);
detailText.setTypeface(helveticaLight);
detailText.setTextColor(Color.parseColor("#a5a5a5"));
if (detailText != null) {
detailText.setText(detail);
}
final TextView idFlagText = (TextView) v.findViewById(R.id.idFlag);
if (idFlagText != null) {
idFlagText.setText(id);
}
trash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(mContext);
deleteDialog.setTitle("Delete Memoir");
deleteDialog.setMessage("Are you sure you want to delete this Memoir?");
deleteDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
drawnImage.setVisibility(View.GONE);
trash.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
dbAdapter.remove(Long.parseLong(id));
notifyDataSetChanged();
cursor = dbAdapter.getAllRows();
changeCursor(cursor);
}
});
deleteDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
deleteDialog.show();
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, AddItem.class);
intent.putExtra("Description", description);
intent.putExtra("Detail", detail);
intent.putExtra("ImportanceLevel", importance);
intent.putExtra("Id", id);
mContext.startActivity(intent);
}
});
}
}

Nothing to deleted checked item in listview in android

I am trying to deleted checked item in listview in android, but I haven't achive this, why? my code is below. please response . I have try this code as well , which has not get more idea.
How to delete check box items from list
and many more related to delete list item form list view.
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static String[] tempTitle = new String[100];
static String[] tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle[position]);
holder.text2.setText(tempBody[position]);
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.length;b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
tempTitle = one.split(",");
tempBody = two.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}
please update this code with no errors. Or give be best idea for this.
You are removing items from a list while traversing it. At least you must make sure to account for the removed item in the counter variable and the list size (which is why there is an i-- in the original code, but you have commented it out).
I.e. after you deleted the item with index 2, the next in the list is still 2, not 3.
Un-comment the i--, that should fix it.
you want to delete checked item, but not modifying data source of list, please load data source from checks list. as Below:
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static ArrayList<String> tempTitle = new String[100];
static ArrayList<String> tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle.get(position));
holder.text2.setText(tempBody.get(position));
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.size();b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
String[] tokens = one.split(",");
tempTitle=Arrays.asList(tokens);
tokens= two.split(",");
tempBody =Arrays.asList(tokens);
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
tempTitle.remove(i);
tempBody.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}

Categories

Resources