Setting TextViews from an onClick(View v) within an onClick(View v)? - android

This line will not set, holder.t1.setText(NewItem);
If I move it to the parent onClick, with a hardcoded string (for testing) it does.
Keep in mind, this is inside a getView method of an ArrayAdapter. I am trying to setText to ListView rows.
Edit:
EXPANDED, COMPLETE getView() -- AS REQUESTED
(Did not have time to edit, will later, sorry!)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.commentlayout, parent,
false);
holder = new ViewHolder();
holder.t1 = (TextView) convertView.findViewById(R.id.labelComment);
holder.t2 = (TextView) convertView.findViewById(R.id.labelDate);
holder.t3 = (TextView) convertView.findViewById(R.id.labelUser);
holder.t3.setTypeface(tf);
holder.t4 = (TextView) convertView
.findViewById(R.id.labelHelpfulCount);
holder.t5 = (TextView) convertView
.findViewById(R.id.labelCommentCount);
holder.ib1 = (ImageView) convertView
.findViewById(R.id.labelChatIcon);
holder.ib2 = (ImageView) convertView
.findViewById(R.id.labelCommentFlag);
holder.rb1 = (RatingBar) convertView
.findViewById(R.id.myCommentsRatingBarSmall);
holder.b1 = (Button) convertView.findViewById(R.id.bReview1);
holder.b2 = (Button) convertView.findViewById(R.id.bReview2);
holder.b3 = (Button) convertView.findViewById(R.id.bReview3);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
convertView.setOnCreateContextMenuListener(null);
}
ReviewObject ro = getItem(position);
final String item = ro.item;
final String review = ro.review;
final String username = ro.username;
Long date = Long.valueOf(ro.date);
String rating = ro.ratings;
String voteCount = ro.voteCount;
String chatcount = ro.chatCount;
String cat = ro.cat;
final ArrayList<String> passing = new ArrayList<String>();
passing.add(item);
passing.add(review);
passing.add(cat);
passing.add(username);
String time = "";
time = DateConvert.dateConvert(Long.valueOf(date));
holder.t1.setText(review);
holder.t2.setText(time);
holder.t3.setText(username);
holder.t4.setText(voteCount);
holder.t5.setText(chatcount);
holder.ib1.setImageResource(R.drawable.updown);
holder.ib2.setImageResource(R.drawable.comment);
holder.rb1.setRating(Float.valueOf(rating));
if (rating.equals("0")) {
holder.rb1.setEnabled(false);
}
holder.b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String ReviewUser = holder.t3.getText().toString();
String ReviewWords = holder.t1.getText().toString();
Intent intent = new Intent(getContext(), Comments.class);
intent.putExtra("comment", ReviewWords);
intent.putExtra("user", ReviewUser);
intent.putExtra("item", item);
getContext().startActivity(intent);
}
});
if (!Rateit.username.equals(username)) {
holder.b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(getContext());
alertbox.setMessage("Did you like this?");
alertbox.setNegativeButton("Vote Up",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface arg0,
int arg1) {
String VoteTally = holder.t4.getText()
.toString();
int ReviewCountInt = Integer
.valueOf(VoteTally) + 1;
VoteTally = String.valueOf(ReviewCountInt);
holder.t4.setText(VoteTally);
new HelpfulTask().execute(passing);
}
});
alertbox.setPositiveButton("Vote Down",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog,
int id) {
String VoteTally = holder.t4.getText()
.toString();
int ReviewCountInt = Integer
.valueOf(VoteTally) - 1;
VoteTally = String.valueOf(ReviewCountInt);
holder.t4.setText(VoteTally);
new UnHelpfulTask().execute(passing);
}
});
alertbox.setNeutralButton("Report Spam",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog,
int id) {
new SpamTask().execute(passing);
}
});
alertbox.show();
}
});
} else {
holder.b2.setText("Edit");
holder.b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.editreview);
dialog.setTitle("Edit Review");
dialog.show();
final EditText etEdit = (EditText) dialog
.findViewById(R.id.etEditReview);
etEdit.setText(review);
Button bInsert = (Button) dialog.findViewById(R.id.bInsert);
bInsert.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
NewItem = etEdit.getText().toString();
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
} else {
holder.t1.setText(NewItem);
passing.add(NewItem);
dialog.dismiss();
new EditCommentTask().execute(passing);
}
}
});
}
});
}
if (!Rateit.username.equals(username)) {
holder.b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getContext(), OtherProfile.class);
i.putExtra("userprofile", username);
getContext().startActivity(i);
}
});
} else {
holder.b3.setText("Delete");
holder.b3.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
getContext());
alertbox.setMessage("Are you sure you want to delete your review?");
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
new DeleteReviewTask().execute(passing);
}
});
alertbox.show();
}
});
}
return convertView;
}

From what you've said in the above comments, this is the intended function. Since,
Except, the dialog does dismiss, I get the toast and the task runs correctly.
This is coded into your onClick() here:
bInsert.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
NewItem = etEdit.getText().toString();
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
} else {
holder.t1.setText(NewItem);
passing.add(NewItem);
dialog.dismiss();
new EditCommentTask().execute(passing);
}
}
});
Specifically, this is executing:
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
}
so I am assuming your problem is with NewItem, I never see where you actually initialize it, but I am assuming it .equals("") since this is executing. Try throwing a Log.d or println() just below the line NewItem = etEdit.getText().toString(); to see what the value of NewItem is at this point.

Related

clicking on a listview item

I have a ListView in my app and each item in the ListView contains a button and item count in it.While clicking on the button in each item, I want to show a dialogue with an EditText to enter new count of the corresponding item and update the item with the value which i get from the dialogue EditText field.
I created dialogue to enter new count on button click, but can't update the value.
My adapter
public class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return planList.size();
}
#Override
public Object getItem(int position) {
return planList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SalesModel db_data = planList.get(position);
if (convertView == null) {
convertView = View.inflate(getApplicationContext(), R.layout.return_confirm, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
final TextView stock = (TextView) convertView.findViewById(R.id.stock);
TextView amount = (TextView) convertView.findViewById(R.id.amount);
ImageView minus = (ImageView) convertView.findViewById(R.id.minus);
Double count = Double.parseDouble(db_data.getStock());
Double price = Double.parseDouble(db_data.getSprice());
Double s_price = count*price;
String set_amount = s_price.toString();
name.setText(db_data.getName());
stock.setText(db_data.getStock());
amount.setText(set_amount);
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stock_return = ShowDialogue();
Double n_stock = Double.parseDouble(db_data.getStock())-Double.parseDouble(stock_return);
stock.setText(n_stock.toString());
}
});
return convertView;
}
}
Function to show dialogue
public String ShowDialogue(){
String stk_val;
stock_return = "0.0";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.popup_reminder, null);
final EditText stk = (EditText)dialogLayout.findViewById(R.id.stock);
Button ok = (Button)dialogLayout.findViewById(R.id.later );
Button close = (Button)dialogLayout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(stk.getText().toString().trim().isEmpty()){
stk.setError("Enter quantity");
}
else {
stock_return = stk.getText().toString().trim();
}
}
});
dialog.setView(dialogLayout,0,0,0,0);
dialog.show();
return stock_return;
}
you doing something wrong.
Dialog cannot return before you enter ok button.
Try like this :
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stock_return = ShowDialogue(this, position);
}
});
Change dialog to accordance with it like this..
public void ShowDialogue(MyAdapter myAdapter, int position){
String stk_val;
stock_return = "0.0";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.popup_reminder, null);
final EditText stk = (EditText)dialogLayout.findViewById(R.id.stock);
Button ok = (Button)dialogLayout.findViewById(R.id.later );
Button close = (Button)dialogLayout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(stk.getText().toString().trim().isEmpty()){
stk.setError("Enter quantity");
}
else {
planList.get(position).setStock(stk.getText().toString().trim());
dialog.dismiss();
myAdapter.notifyDataSetChanged();
}
}
});
dialog.setView(dialogLayout,0,0,0,0);
dialog.show();
}

ListView lost focus

I am working on an app in android studio.
My app has a listview, whiche has Edittext , textview and checkbox in its row.
my proplem is when I have more than five items in my listvew, the listview lost focus, for example: when I press on checkbox on the 6th item , the textview shows me the name from the first item.
I wish I could explain my proplem very well.
This is my adapter:
public AdapterListView(Context context, int resource, ArrayList<ObjectPeople> arraypeople) {
super(context, resource);
this.mContext = context;
this.arrayPeople = arraypeople;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.mission_name = (TextView) convertView.findViewById(R.id.mission_name);
holder.mission_time = (TextView) convertView.findViewById(R.id.mission_time);
holder.edit_time = (EditText) convertView.findViewById(R.id.edit_time);
holder.mission_image= (ImageView) convertView.findViewById(R.id.mission_image);
holder.cbm = (CheckBox) convertView.findViewById(R.id.checkbo);
convertView.setTag(holder);
holder.cbm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v ) {
CheckBox cb = (CheckBox) v ;
final ObjectPeople person = arrayPeople.get(position);
if(cb.isChecked()) {
arrayPeople.get(position).checkbox= true;
int mis_tm=0;
try{ mis_tm= Integer.parseInt( holder.edit_time.getText().toString());}
catch (Exception e){
cb.setChecked(false);
Toast.makeText(mContext, "يرجى إدخال قيمة معينة", Toast.LENGTH_SHORT).show();}
person.time= mis_tm;
if(mis_tm>0&&mis_tm<1200){
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: "+ person.time );
holder.edit_time.setVisibility(View.GONE);}
else{
cb.setChecked(false);
Toast.makeText(mContext, "يرجى اختيار رقم حقيقي", Toast.LENGTH_SHORT).show();
}
}
else {
arrayPeople.get(position).checkbox= false;
holder.edit_time.setVisibility(View.VISIBLE);
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
final ObjectPeople person = arrayPeople.get(position);
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: ");
holder.mission_image.setImageResource(arrayPeople.get(position).image);
holder.edit_time.setId(position);
holder.edit_time.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
try {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayPeople.get(position).time = Integer.parseInt(Caption.getText().toString());
}
}catch (Exception e){}
}
});
holder.cbm.setTag(arrayPeople);
return convertView;
}
#Override
public int getCount() {
return arrayPeople.size();
}
static class ViewHolder {
TextView mission_name;
TextView mission_time;
EditText edit_time;
ImageView mission_image;
CheckBox cbm;
}
}
and this select.java which contains the arraylist and list view:
public class select extends AppCompatActivity {
ArrayList<ObjectPeople> arrPeople;
ListView lvPeople;
AdapterListView adapter;
ObjectPeople person;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
settings = getApplicationContext().getSharedPreferences("shared", 0);
lvPeople= (ListView) findViewById(R.id.lvPeopl);
arrPeople=new ArrayList<>();
person = new ObjectPeople("حفظ قرآن", 0,false, R.drawable.quran_hifz_r);
arrPeople.add(person);
person = new ObjectPeople("تلاوة قرآن", 0 ,false,R.drawable.img);
arrPeople.add(person);
person = new ObjectPeople("قراءة كتاب", 0 , false,R.drawable.books_r);
arrPeople.add(person);
person = new ObjectPeople("دورات تطوير مهارات", 0 , false,R.drawable.courses_r);
arrPeople.add(person);
person = new ObjectPeople("رياضة", 15 , false,R.drawable.sport_r);
arrPeople.add(person);
final String[] misson_name = new String[1];
Button adf= (Button) findViewById(R.id.add_mission_out_btn);
adf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(select.this).inflate(R.layout.add_mission_lyt,null);
final EditText add_name = (EditText) view.findViewById(R.id.add_mission_name);
AlertDialog.Builder builder = new AlertDialog.Builder(select.this);
builder.setMessage("add your mission")
.setView(view)
.setPositiveButton("إضافة", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
misson_name[0] = add_name.getText().toString();
arrPeople.add(new ObjectPeople(misson_name[0], 0, true,R.drawable.smile_small_r));
}
})
.setNegativeButton("إلغاء",null)
.setCancelable(false);
AlertDialog alert =builder.create();
alert.show();
}
});
adapter=new AdapterListView(this,R.layout.item_listview,arrPeople);
lvPeople.setAdapter(adapter);
checkButtonClick();
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.btn_save);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", 0);
int hours2=settings.getInt("hours",0)*60;
ArrayList<ObjectPeople> selected_missions = new ArrayList<>();
int missoins_time_calc=0;
for (int i = 0; i <arrPeople.size(); i++) {
if(arrPeople.get(i).checkbox==true){
selected_missions.add(arrPeople.get(i));
missoins_time_calc= missoins_time_calc + arrPeople.get(i).time;}
}
if (hours2 == missoins_time_calc){
Gson gson = new Gson();
String jsonText = gson.toJson(selected_missions);
SharedPreferences.Editor editor = settings.edit();
editor.putString("selected_array", jsonText);
editor.commit();
Intent intent = new Intent(select.this, yourprogram.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
else if (hours2 > missoins_time_calc){
Toast.makeText(select.this, "بقي"+(-missoins_time_calc+ hours2)+" دقيقة ", Toast.LENGTH_SHORT).show();}
else if (hours2< missoins_time_calc){
Toast.makeText(select.this,"يوجد "+ (-hours2+missoins_time_calc)+" دقيقة زيادة على الوقت المخصص", Toast.LENGTH_SHORT).show();
}
/* ArrayList<missions> missionsList = dataAdapter.missionsList;
for(int i = 0; i< missionsList.size(); i++){
missions missions = missionsList.get(i);
if(missions.isSelected()){}}*/
}
});
}
}
I think the error is the way your arrayPeople List is being populated, if you say the sixth item gets you the first you can try reversing the order with
Collections.reverse(arrayPeople);
you can place this line of code below your holder.cbm.setOnClickListener on your adapter
Hope it helps.

Button can not hidden when spinner show in listview adapter

I have a code in adapter listview. I want to hide the button "image2" when show listview, but it doesn't work. Where is my fault? Anyone can help me?
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Database = new SQLite(context);
db = Database.getReadableDatabase();
if (convertView == null) {
inflater = context.getLayoutInflater();
convertView = inflater.inflate(resource, null);
}
final Model_CheckStock itempos = ListViewCheckStock.get(position);
TextView txproduk = (TextView) convertView.findViewById(R.id.txproduk);
final TextView txqty = (TextView) convertView.findViewById(R.id.txqty);
final TextView txexpired = (TextView) convertView.findViewById(R.id.txexpired);
TextView txidproduk = (TextView) convertView.findViewById(R.id.txidproduk);
final Spinner spin = (Spinner) convertView.findViewById(R.id.spin);
ImageView imgexpired = (ImageView) convertView.findViewById(R.id.imgexpired);
Button image = (Button) convertView.findViewById(R.id.image);
final Button image2 = (Button) convertView.findViewById(R.id.image2);
txproduk.setText(ListViewCheckStock.get(position).gettxproduk());
txidproduk.setText("Produk " + ListViewCheckStock.get(position).getjnsprod());
txqty.setText(ListViewCheckStock.get(position).gettxqty());
txexpired.setText(ListViewCheckStock.get(position).getexpired());
// image2.setVisibility(View.INVISIBLE);
if (txidproduk.getText().toString().contains("NON")) {
Log.w("ADAPTERCHECKSTOCKLIST", "getView non: "+txidproduk.getText().toString() );
List<Model_Unit> chekstok = Database.getUnitAll();
ArrayAdapter<Model_Unit> dataAdapter = new ArrayAdapter<Model_Unit>(
context, android.R.layout.simple_spinner_item, chekstok);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
spin.setSelection(getIndex(spin, ListViewCheckStock.get(position).getunit()));
image2.setVisibility(View.INVISIBLE);
notifyDataSetChanged();
} else {
Log.w("ADAPTERCHECKSTOCKLIST", "getView sgf: "+txidproduk.getText().toString() );
List<Model_Unit> chekstok = Database.getUnit(ListViewCheckStock.get(position).getidprod());
ArrayAdapter<Model_Unit> dataAdapter = new ArrayAdapter<Model_Unit>(
context, android.R.layout.simple_spinner_item, chekstok);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
spin.setSelection(getIndex(spin, ListViewCheckStock.get(position).getunit()));
image2.setVisibility(View.INVISIBLE);
notifyDataSetChanged();
}
imgexpired.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatePickerDialog();
myCalendar = Calendar.getInstance();
dialog = new DatePickerDialog(context,
dateListener, year, month, day);
dialog.show();
image2.setVisibility(View.VISIBLE);
}
});
image2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(
context);
dialog.setMessage("Anda Yakin Ingin Menyimpan Perubahan Data Ini ?");
dialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String saving;
saving = String.valueOf((ListViewCheckStock.get(position).getidtable()));
System.out.println("saving" + saving);
db = Database.getWritableDatabase();
Database.updateSavingCheckstok(ListViewCheckStock.get(position).getunit(), saving, ListViewCheckStock.get(position).gettxqty(), ListViewCheckStock.get(position).getexpired());
image2.setVisibility(View.GONE);
}
});
dialog.setNegativeButton("Kembali",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
});
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int arg2, long id) {
if ((txqty.getText().toString().contains(".") && !spin.getSelectedItem().toString().equals("CAR")) &&
(txqty.getText().toString().contains(".") && !spin.getSelectedItem().toString().equals("KG"))) {
CustomDialog.init.setDialog(context,
"Format angka", "Desimal tidak diperbolehkan dalam unit ini.",
"ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
txqty.setText("");
}
});
}
String prod;
ListViewCheckStock.get(position).setunit(adapterView.getSelectedItem().toString());
Log.w("TAG >>", "onItemSelected: " + ListViewCheckStock.get(position).getunit());
spin.setSelection(arg2);
image2.setVisibility(View.VISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private int getIndex(Spinner spinner, String myString) {
int index = -1;
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString()
.equalsIgnoreCase(myString)) {
index = i;
break;
}
}
return index;
}
}
i want to hide the save button (image2) when listview is show.but the button always show.
and then, when flagstatus is not 0 the button still show.

Refresh Does not work at update time

public class ListViewAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
DatabaseHelper mydb;
int pos = 0;
enter code here
public ArrayList<Employee_info> mArrayList = new ArrayList<Employee_info>();
public ListViewAdapter(Context context,ArrayList<Employee_info> arrayList){
mContext=context;
mArrayList=arrayList;
mLayoutInflater=LayoutInflater.from(mContext);
mydb = new DatabaseHelper(mContext);
}
enter code here
#Override
public int getCount() {
return mArrayList.size();
}
enter code here
#Override
public Object getItem(int position) {
return mArrayList.get(position);
}
enter code here
#Override
public long getItemId(int position) {
return position;
}
enter code here
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=new ViewHolder();
View view=convertView;
if(view == null){
//view = mLayoutInflater.inflate(R.layout.list_view,parent,false);
view = mLayoutInflater.inflate(R.layout.list_view,null);
holder.txtName = (TextView)view.findViewById(R.id.txtName);
holder.txtCode = (TextView)view.findViewById(R.id.txtCode);
holder.txtStatus = (TextView)view.findViewById(R.id.txtStatus);
//// Start //////////////
Button b1 = (Button) view.findViewById(R.id.button1);
Button b2 = (Button) view.findViewById(R.id.button2);
Button b3 = (Button) view.findViewById(R.id.button3);
b1.setTag(position);
final Employee_info emp_info = mArrayList.get(position);
b2.setTag(position);
b3.setTag(position);
final ViewHolder finalHolder = holder;
b3.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
int x = (int) v.getTag();
/* if (itemPos.contains(v)) {
finalHolder.txtCode.setTextColor(Color.RED);
finalHolder.txtName.setTextColor(Color.RED);
finalHolder.txtStatus.setTextColor(Color.RED);
}
else {*/
if (mArrayList.get(x).getGet_status() != null) {
if (mArrayList.get(x).getGet_status().equals("Unpaid")) {
String upd1 = mArrayList.get(x).getGet_code();
String upd2 = mArrayList.get(x).getGet_name();
String upd3 = "Paid";
mydb.UpdateData(upd1, upd2, upd3);
// THis code for only catch Month, year, Employee ID, Status
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
String month_name = month_date.format(cal.getTime());
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
mydb.insertEmpSalary(upd1, month_name, String.valueOf(thisYear), upd3);
finalHolder.txtStatus.setTextColor(Color.GREEN);
ListViewAdapter.this.notifyDataSetChanged();
} else {
String upd1 = mArrayList.get(x).getGet_code();
String upd2 = mArrayList.get(x).getGet_name();
String upd3 = "Unpaid";
mydb.UpdateData(upd1, upd2, upd3);
finalHolder.txtStatus.setTextColor(Color.RED);
}
}
}
//}
});
b1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(final View position) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Confirm");
builder.setMessage("Are you sure?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
pos = (int) position.getTag();
mydb.deleteData(mArrayList.get(pos).getGet_code());
mArrayList.remove(pos);
ListViewAdapter.this.notifyDataSetChanged();
Toast.makeText(mContext, mArrayList.get(pos).getGet_code() + " Employee is Delete", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Alert Dialog With EditText"); //Set Alert dialog title here
alert.setMessage("Enter Your Code");
pos = (int) v.getTag();
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText input = new EditText(mContext);
input.setText(mArrayList.get(pos).getGet_code());
layout.addView(input);
final EditText input1 = new EditText(mContext);
input1.setText(mArrayList.get(pos).getGet_name());
layout.addView(input1);
final EditText input2 = new EditText(mContext);
input2.setText(mArrayList.get(pos).getGet_status());
layout.addView(input2);
alert.setView(layout);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try
{
String srt = input.getEditableText().toString();
Log.d("ccccccc", srt);
String upd1 = input.getText().toString();
String upd2 = input1.getText().toString();
String upd3 = input2.getText().toString();
/*String upd1 = mArrayList.get(pos).getGet_code();
String upd2 = mArrayList.get(pos).getGet_name();
String upd3 = mArrayList.get(pos).getGet_status();
Log.d("Code1",mArrayList.get(pos).getGet_code());
Log.d("Name1",mArrayList.get(pos).getGet_name());
Log.d("Status1",mArrayList.get(pos).getGet_status());*/
Log.d("Code",upd1);
Log.d("Name", upd2);
Log.d("Status", upd3);
boolean isUpdate = mydb.UpdateData(upd1, upd2, upd3);
ListViewAdapter.this.notifyDataSetChanged();
notifyDataSetChanged();
if (isUpdate == true)
{
Log.e("Update Complete", String.valueOf(isUpdate));
ListViewAdapter.this.notifyDataSetChanged();
Toast.makeText(mContext, srt + " Employee is Updated", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(mContext, srt + " Employee is not Updated", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
dialog.dismiss();
}
});
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
});
view.setTag(holder);
} else {
holder=(ViewHolder)view.getTag();
}
Employee_info employee_info = mArrayList.get(position);
holder.txtName.setText(employee_info.getGet_name());
holder.txtCode.setText(employee_info.getGet_code());
holder.txtStatus.setText(employee_info.getGet_status());
return view;
}
private class ViewHolder{
private TextView txtName,txtCode,txtStatus;
public Button b1;
}
}
You can't add values in getView. let's do it in activity

ListView CheckBox getting multi selected on just clicking only one time

I'm trying to use CheckBox in my ListView with an ArrayAdapter. When I select any CheckBox onlytime in the list, multiple entries are selected automatically in a random order. Can anyone please tell how I can avoid this.
Here's my code for your reference:
public class SearchListAdapterQ2 extends BaseAdapter {
int layoutId;
ArrayList<SearchListView> searchresultList = new ArrayList<SearchListView>();
public static int companyCpsId;
public static String companyCpsType = "", search_companyName = "",
search_countryName = "", handShakeStatus = "";
public static String handShakeCPSName = "";
public static boolean searchListAdapter_Q2 = false;
SharedPreferences sharedpreferences;
boolean markfavStatus = false;
ListView searchResults_listView;
Context context;
public SearchListAdapterQ2(Context context, int layoutId,
ArrayList<SearchListView> searchresultList,
ListView searchResults_listView) {
// TODO Auto-generated constructor stub
this.layoutId = layoutId;
this.searchresultList = searchresultList;
Log.i("inside searchListAdapter", "inside searchListAdapter");
this.context = context;
sharedpreferences = context.getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
this.searchResults_listView = searchResults_listView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.i("searchresultList",
"searchresultList: " + searchresultList.size());
return searchresultList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return searchresultList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder1 holder1;
// LayoutInflater inflater = (LayoutInflater)
// context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
char color;
String text = "";
String address = "";
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.qq_searchlist_repeat_items,
parent, false);
holder1 = new ViewHolder1();
holder1.companyName_textView = (TextView) convertView
.findViewById(R.id.companyName_textView);
holder1.companyLogo_textView = (TextView) convertView
.findViewById(R.id.companyLogo_textView);
holder1.companyAddress_textView = (TextView) convertView
.findViewById(R.id.companyAddress_textView);
holder1.handShakeIcon_imageView = (ImageView) convertView
.findViewById(R.id.handShakeIcon_imageView);
holder1.favouritesIcon_imageView = (ImageView) convertView
.findViewById(R.id.favouritesIcon_imageView);
holder1.referIcon_imageView = (ImageView) convertView
.findViewById(R.id.referIcon_imageView);
holder1.sendEnquiry_imageView = (ImageView) convertView
.findViewById(R.id.sendEnquiry_imageView);
holder1.icons_searchResultsPage_relLayout = (RelativeLayout) convertView
.findViewById(R.id.icons_searchResultsPage_relLayout);
holder1.chckbx1 = (CheckBox) convertView.findViewById(R.id.chckbx1);
if (SearchListActivity_Q2.broadcastMode) {
Log.i("icons_searchResultsPage_relLayout is visible",
"icons_searchResultsPage_relLayout is visible");
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.GONE);
holder1.chckbx1.setVisibility(View.VISIBLE);
} else {
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.VISIBLE);
holder1.chckbx1.setVisibility(View.GONE);
}
convertView.setTag(holder1);
} else {
holder1 = (ViewHolder1) convertView.getTag();
}
holder1.id = position;
search_companyName = searchresultList.get(position).getCpsName();
search_countryName = searchresultList.get(position).getCountryName();
try {
String ssearch_companyName = URLDecoder.decode(search_companyName,
"UTF-8");
holder1.companyName_textView.setText(ssearch_companyName);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (searchresultList.get(position).getCpsName().contains(" ")) {
String[] splitText = searchresultList.get(position).getCpsName()
.split("\\s+");
char a = splitText[0].charAt(0);
char b = splitText[1].charAt(0);
text = String.valueOf(a) + String.valueOf(b);
color = b;
} else {
text = searchresultList.get(position).getCpsName().substring(0, 1);
color = searchresultList.get(position).getCpsName().charAt(1);
}
holder1.companyLogo_textView.setText(text.toUpperCase());
if (searchresultList.get(position).getCpsAddress().isEmpty()) {
address = searchresultList.get(position).getCountryName();
} else {
if (searchresultList.get(position).getCpsAddress().length() > 1) {
address = searchresultList.get(position).getCpsAddress() + ", "
+ searchresultList.get(position).getCountryName();
} else {
address = searchresultList.get(position).getCountryName();
}
}
holder1.companyAddress_textView.setText(address);
holder1.companyName_textView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchListAdapter_Q2 = true;
companyCpsId = searchresultList.get(position)
.getCpsId();
Log.i("$$$ companyCpsId", "companyCpsId" + companyCpsId);
companyCpsType = searchresultList.get(position)
.getCpsType();
Intent intent = new Intent(context,
CompanyProfile_Activity.class);
context.startActivity(intent);
}
});
holder1.referIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder1.sendEnquiry_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Q2_SendEnquiryList> sendEnquiry = new ArrayList<Q2_SendEnquiryList>();
sendEnquiry.add(new Q2_SendEnquiryList(searchresultList
.get(position).getCpsId(), searchresultList
.get(position).getCpsName()));
sendEnquiry.add(new Q2_SendEnquiryList(1, "abcdefgh"));
sendEnquiry.add(new Q2_SendEnquiryList(2, "abcdefg"));
sendEnquiry.add(new Q2_SendEnquiryList(3, "abcdef"));
sendEnquiry.add(new Q2_SendEnquiryList(4, "abcde"));
sendEnquiry.add(new Q2_SendEnquiryList(5, "abcd"));
sendEnquiry.add(new Q2_SendEnquiryList(6, "abc"));
sendEnquiry.add(new Q2_SendEnquiryList(7, "ab"));
Intent intent = new Intent(context,
Q2_SendEnquiryActivity.class);
intent.putParcelableArrayListExtra("sendEnquiry",
sendEnquiry);
context.startActivity(intent);
}
});
holder1.handShakeIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
companyCpsId = searchresultList.get(position)
.getCpsId();
handShakeCPSName = searchresultList.get(position)
.getCpsName();
handShakeStatus = searchresultList.get(position)
.getHandShakeStatus();
ConstantVariables.handShakeFromAdapter = true;
if (sharedpreferences.getInt("userId_sp", 0) != 0) {
if (sharedpreferences.getInt("profileActiveStatus",
0) > 0) {
if (sharedpreferences.getInt("organizationId",
0) != 0) {
if (handShakeStatus.equalsIgnoreCase("d")) {
ConstantVariables
.handShakeRequest(
context,
companyCpsId,
0,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position);
} else if (handShakeStatus
.equalsIgnoreCase("p")) {
ConstantVariables
.handShakeRequestAccept(
context,
companyCpsId,
1,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position,
handShakeCPSName);
}
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
context);
// Setting Dialog Title
// alertDialog.setTitle("Please Add Company");
// Setting Dialog Message
alertDialog
.setMessage("Please add your company details");
// Setting Positive "Yes" Button
alertDialog
.setPositiveButton(
"Add",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent intent = new Intent(
context,
Profile_Activity.class);
context.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog
.setNegativeButton(
"Later",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
} else {
ConstantVariables
.requestEmailVerification(context);
}
} else {
ConstantVariables.requestLogin(context);
}
}
});
holder1.favouritesIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
static class ViewHolder1 {
TextView companyName_textView, companyAddress_textView,
companyLogo_textView;
ImageView handShakeIcon_imageView, favouritesIcon_imageView,
referIcon_imageView, sendEnquiry_imageView;
CheckBox chckbx1;
int id;
RelativeLayout icons_searchResultsPage_relLayout;
}
}
in your adapter getView() method set the status of the clicked checkbox in model and call notify data set changed, try that
I added the following lines with my code and it started working fine:
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
final Integer index = new Integer(position);
holder1.chckbx1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// if checked, we add it to the list
checkedPositions.add(index);
} else if (checkedPositions.contains(index)) {
// else if remove it from the list (if it is present)
checkedPositions.remove(index);
}
}
});
// set the state of the checbox based on if it is checked or not.
holder1.chckbx1.setChecked(checkedPositions.contains(index));

Categories

Resources