My issue is regarding listview multiple buttons click. e.g. my list view contain 3 rows and each row contains 3 buttons. when i click on first button in first row it changes color in last row first button
please check image you will know the problem
I have tried to solve it using button tags, view holder, tried to assign position to button but still nothing happened
public class ViewOrderAdapter extends BaseAdapter {
#SuppressWarnings("unused")
private LayoutInflater mInflater;
Context mcontext;
ArrayList<ViewOrder> view_order_array = null;
SimpleDateFormat sdf;
String currentTime;
String ord_id;
public Button accept_btn, pickup_btn, delieverd_btn, order_view, rest_address, cust_address;
GPSTracker gps;
String latitude, longitude;
private static int ipos;
boolean[] buttonState;
AlertDialog alert;
View view;
OrdersFragment ord_frag;
ViewOrderAdapter view_order_adapter1;
public static final String PREFS_NAME = "MyApp_Settings";
SharedPreferences settings;
SharedPreferences.Editor editor;
SharedPreferences prefs;
public ViewOrderAdapter (Context context, ArrayList<ViewOrder> view_order_array) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mcontext = context;
prefs = mcontext.getSharedPreferences(PREFS_NAME, mcontext.MODE_PRIVATE);
this.view_order_array = view_order_array;
buttonState = new boolean[view_order_array.size()];
gps = new GPSTracker(mcontext);
}
#Override
public int getCount() {
return view_order_array.size();
}
#Override
public Object getItem(int position) {
return view_order_array.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("ViewHolder")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.order_single_row, parent, false);
view = convertView;
sdf = new SimpleDateFormat("HH:mm:ss");
currentTime = sdf.format(new Date());
final ViewOrder v_ordr = view_order_array.get(position);
TextView cname = (TextView)convertView.findViewById(R.id.restaurant_name_view);
cname.setText(v_ordr.getRestaurant());
TextView caddr = (TextView)convertView.findViewById(R.id.restaurant_address_view);
caddr.setText(v_ordr.getRaddress());
accept_btn = (Button)convertView.findViewById(R.id.order_accept_btn);
pickup_btn = (Button)convertView.findViewById(R.id.order_pickup_btn);
delieverd_btn = (Button)convertView.findViewById(R.id.order_delievery_btn);
accept_btn.setTag(position);
pickup_btn.setTag(position);
delieverd_btn.setTag(position);
order_view = (Button)convertView.findViewById(R.id.order_info);
rest_address = (Button)convertView.findViewById(R.id.rest_addrs);
cust_address = (Button)convertView.findViewById(R.id.cstom_addrs);
int id = Integer.parseInt(view_order_array.get(position).getId());
accept_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
AppConstants.btn_id = view_order_array.get(position).getId();
String id = AppConstants.btn_id;
//accept_btn.setId(position);
buttonState[position] = false;
String token = AppPreferences.getSharedPrefValue(mcontext, AppConstants.auth);
ShowMessagesDialogsUtitly.showProgressDialog(mcontext);
RequestParams requestParams = new RequestParams();
requestParams.put("k", token);
requestParams.put("id", id); //order id
requestParams.put("status", Integer.toString(1));
requestParams.put("time", currentTime);
requestParams.put("page", "send");
HttpUtils.httpPostRequest(AppConstants.BASE_URL, requestParams, new HttpResponseCallback() {
#Override
public void onCompleteHttpResponse(String whichUrl, String jsonResponse) {
ShowMessagesDialogsUtitly.hideProgressDialog();
if (jsonResponse != null) {
try {
JSONObject jsonResponseObj = new JSONObject(jsonResponse);
if (jsonResponseObj.getInt("status") == 1) {
accept_btn.setBackgroundColor(Color.GRAY);
Intent n = new Intent(mcontext, Order.class);
mcontext.startActivity(n);
((Activity)mcontext).finish();
} else {
Toast.makeText(mcontext, "Order progress error", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
AppUtilites.printStackTrace(e);
}
} else {
Toast.makeText(mcontext, AppConstants.SERVER_ERROR, Toast.LENGTH_SHORT).show();
}
}
});
}
});
pickup_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AppConstants.btn_id = view_order_array.get(position).getId();
String id = AppConstants.btn_id;
String token = AppPreferences.getSharedPrefValue(mcontext, AppConstants.auth);
pickup_btn.setId(position);
ShowMessagesDialogsUtitly.showProgressDialog(mcontext);
RequestParams requestParams = new RequestParams();
requestParams.put("k", token);
requestParams.put("id", id); //order id
requestParams.put("status", Integer.toString(2));
requestParams.put("time", currentTime);
requestParams.put("page", "send");
HttpUtils.httpPostRequest(AppConstants.BASE_URL, requestParams, new HttpResponseCallback() {
#Override
public void onCompleteHttpResponse(String whichUrl, String jsonResponse) {
ShowMessagesDialogsUtitly.hideProgressDialog();
if (jsonResponse != null) {
try {
JSONObject jsonResponseObj = new JSONObject(jsonResponse);
Toast.makeText(mcontext, "Order accepted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Order order not accepted", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
AppUtilites.printStackTrace(e);
}
} else {
Toast.makeText(mcontext, AppConstants.SERVER_ERROR, Toast.LENGTH_SHORT).show();
}
}
});
}
});
delieverd_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AppConstants.btn_id = view_order_array.get(position).getId();
String id = AppConstants.btn_id;
String token = AppPreferences.getSharedPrefValue(mcontext, AppConstants.auth);
delieverd_btn.setId(position);
ShowMessagesDialogsUtitly.showProgressDialog(mcontext);
RequestParams requestParams = new RequestParams();
requestParams.put("k", token);
requestParams.put("id", id); //order id
requestParams.put("status", Integer.toString(3));
requestParams.put("time", currentTime);
requestParams.put("page", "send");
HttpUtils.httpPostRequest(AppConstants.BASE_URL, requestParams, new HttpResponseCallback() {
#Override
public void onCompleteHttpResponse(String whichUrl, String jsonResponse) {
ShowMessagesDialogsUtitly.hideProgressDialog();
if (jsonResponse != null) {
try {
JSONObject jsonResponseObj = new JSONObject(jsonResponse);
if (jsonResponseObj.getInt("status") == 1) {
} else {
Toast.makeText(mcontext, "Order order not delievered", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
AppUtilites.printStackTrace(e);
}
} else {
Toast.makeText(mcontext, AppConstants.SERVER_ERROR, Toast.LENGTH_SHORT).show();
}
}
});
}
});
order_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.order_view_lay, (ViewGroup)view.findViewById(R.id.order_view_lay_id));
AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setView(layout);
alert = builder.create();
TextView order_id = (TextView) layout.findViewById(R.id.order_no);
order_id.setText(view_order_array.get(position).getOid());
TextView rest_name = (TextView) layout.findViewById(R.id.rstarnt_name);
rest_name.setText(view_order_array.get(position).getRestaurant());
TextView quantity = (TextView) layout.findViewById(R.id.quantity);
quantity.setText(view_order_array.get(position).getOid());
TextView item = (TextView) layout.findViewById(R.id.item);
item.setText(view_order_array.get(position).getMenu());
TextView price = (TextView) layout.findViewById(R.id.price);
price.setText(view_order_array.get(position).getAmount());
TextView subtotal = (TextView) layout.findViewById(R.id.sub_total);
subtotal.setText("XXXX");
TextView total = (TextView) layout.findViewById(R.id.total);
total.setText("XXXX");
Button ok = (Button) layout.findViewById(R.id.ok_popup_order_view_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
});
rest_address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.restaurant_addr_lay, (ViewGroup)view.findViewById(R.id.rest_addr_lay_id));
AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setView(layout);
alert = builder.create();
TextView r_name = (TextView) layout.findViewById(R.id.rst_name_popup);
r_name.setText(view_order_array.get(position).getRestaurant());
TextView r_add = (TextView) layout.findViewById(R.id.rst_addr_popup);
r_add.setText(view_order_array.get(position).getRaddress());
TextView r_phone = (TextView) layout.findViewById(R.id.rst_phone_popup);
r_phone.setText(view_order_array.get(position).getRestaurant());
Button map = (Button) layout.findViewById(R.id.map_to_restaurant_popup);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (gps.canGetLocation()) {
latitude = gps.getLatitude() + "";
longitude = gps.getLongitude() + "";
AppConstants.Latitude = latitude.toString();
AppConstants.Longitude = longitude.toString();
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
gps.getCompleteAddressString(lat, lon);
AppConstants.Address_To = view_order_array.get(position).getRaddress();
String addr = AppConstants.Address_To;
gps.getLocationFromAddress(mcontext, addr);
Intent intent = new Intent(mcontext, MapLayout.class);
mcontext.startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
});
Button map_dirct = (Button) layout.findViewById(R.id.directions_to_restaurant_popup);
map_dirct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (gps.canGetLocation()) {
latitude = gps.getLatitude() + "";
longitude = gps.getLongitude() + "";
AppConstants.Latitude = latitude.toString();
AppConstants.Longitude = longitude.toString();
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
gps.getCompleteAddressString(lat, lon);
AppConstants.Address_To = view_order_array.get(position).getRaddress();
Intent intent = new Intent(mcontext, MapLayout.class);
mcontext.startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
});
Button ok = (Button) layout.findViewById(R.id.ok_popup_raddr_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
});
cust_address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.customer_addr_lay, (ViewGroup)view.findViewById(R.id.cust_addr_lay_id));
AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setView(layout);
alert = builder.create();
TextView c_name = (TextView) layout.findViewById(R.id.cst_name_popup);
c_name.setText(view_order_array.get(position).getCustomer());
TextView c_add = (TextView) layout.findViewById(R.id.cst_addr_popup);
c_add.setText(view_order_array.get(position).getCaddress());
TextView c_phone = (TextView) layout.findViewById(R.id.cst_phone_popup);
c_phone.setText(view_order_array.get(position).getCphone());
TextView order_inst = (TextView) layout.findViewById(R.id.cst_order_inst_popup);
order_inst.setText(view_order_array.get(position).getInstruction());
Button map = (Button) layout.findViewById(R.id.map_to_customer_popup);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (gps.canGetLocation()) {
latitude = gps.getLatitude() + "";
longitude = gps.getLongitude() + "";
AppConstants.Latitude = latitude.toString();
AppConstants.Longitude = longitude.toString();
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
gps.getCompleteAddressString(lat, lon);
AppConstants.Address_To = view_order_array.get(position).getCaddress();
Intent intent = new Intent(mcontext, MapLayout.class);
mcontext.startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
});
Button map_direct = (Button) layout.findViewById(R.id.directions_to_customer_popup);
map_direct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (gps.canGetLocation()) {
latitude = gps.getLatitude() + "";
longitude = gps.getLongitude() + "";
AppConstants.Latitude = latitude.toString();
AppConstants.Longitude = longitude.toString();
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
gps.getCompleteAddressString(lat, lon);
AppConstants.Address_To = view_order_array.get(position).getCaddress();
Intent intent = new Intent(mcontext, MapLayout.class);
mcontext.startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
});
Button ok = (Button) layout.findViewById(R.id.ok_popup_caddr_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
});
return convertView;
}
}
Try this simple answer:
find your button view by the tag you have set.
((Button) convertView.findViewWithTag(position)).setBackgroundColor(Color.GRAY);
You are encountering this problem because the last accept_btn object your adapter is holding is the last view object it created.
Therefore you are on the right track by setting a tag on the button. But then you have to retrieve that view by the tag.
Let me know if this is helpful.
Thanks.
I have written answer for same problem in gridview HERE. You can use same trick to solve this issue.
// Brief idea
You can implement your own custom OnClickListener and you can associate id/tag/position for each onclick of each item of listview.
yourBtn.setOnclickListener(new BtnClick(position, btnid));
Custom OnclickListener:
Class BtnClick View.OnClickListener
{
int position;
int btnId;
Public BtnClick(int position, int id)
{
this.position = position;'
this.btnId = btnId;
}
#Override
public onClick(View v)
{
// You can add logic here for each item clicked using position and id of each item you passed in constructor
}
}
Related
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.
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
Hello and greetings i am developing one app that accept multiple images from user and upload to server but images upload to server is ok.I just added one edittext to enter quantity of image but i am unable to get value from that respective edittext.so give me suggestion in my code.
i have edittext in gridview so i want to get text from edittext that is quantity of image so please help me
uploadphoto.java
public class UploadPhotos extends AppCompatActivity {
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
ProgressDialog progressDialog;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
//Toast.makeText(getApplicationContext(),""+strSize+"\n"+strType+"\n"+strMRP+"\n"+strPrice+"\n"+strlab+"\n"+strcity,Toast.LENGTH_LONG).show();
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
abc="EPP"+abc;
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
progressDialog=new ProgressDialog(UploadPhotos.this);
progressDialog.setMessage("Images is Uploading.......");
progressDialog.setCancelable(false);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.mp3));
progressDialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
totalprice=0;
}
Intent i=new Intent(UploadPhotos.this,Digital_Cart.class);
startActivity(i);
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
selectedAdapter.changeSelection(view, position);
}
});
}
private void doFileUpload() {
for( i = 0 ; i<listOfPhotos.size();i++) {
final CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(i);
File f = new File(objDetails.sdcardPath);
imageName = f.getName();
totalprice=totalprice+Long.parseLong(strPrice);
total=String.valueOf(totalprice);
Log.v("Abhijit",""+totalprice);
// Toast.makeText(getApplicationContext(),""+totalprice,Toast.LENGTH_LONG).show();
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://eeee.com/aaaaa/UploadFile?foldername="+abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
// publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strSize));
Log.v("svbh", strSize);
entity.addPart("type",
new StringBody(strType));
entity.addPart("username",
new StringBody(user_mail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strMRP));
entity.addPart("price",
new StringBody(strPrice));
entity.addPart("lab",
new StringBody(strlab));
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag=String.valueOf(i+1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(str_username));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
final String response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Log.i("RESPONSE", response_str + "" + imageName);
runOnUiThread(new Runnable(){
public void run() {
try {
snackbar = Snackbar
.make(coordinatorLayout, i+" image "+response_str, Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
//Toast.makeText(getApplicationContext(),i+" image "+response_str, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
}
and selected_adapter_test
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
And customGallery.java
public class CustomGallery {
public String sdcardPath;
public int qty;
EditText aaa;
public boolean isSeleted;
}
so please help to get text from edittext that is quantity.i cant figure out the problem from last one week.
Thanks in advance
Here is the code :
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.qty.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// save your text here
data.get(i).qty= 1;
}
});
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
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));
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.