ListView doesn't want to refresh - java

I have one problem, I have one activity and one dialogfragment. When I click on button in my dialogfragment I send model to Activity and write this model to the list. But when I add to the list more than one element, my listview duplicate first element, I init my adapter in onCreate() and add new information in onExcerciseAdd:
Activity:
public class AddTrainingActivity extends ActionBarActivity implements ExcercisesFragment.onButtonAdd {
private ActionBarDrawerToggle toggle;
int DIALOG_TIME = 1;
int myHour = 00;
int myMinute = 00;
TextView tvTime;
Button btn_add_ex;
ListView list;
ExcerciseAdapter adapter;
ArrayList<ExcerciseModel> excercise_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addtraining);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvTime = (TextView) findViewById(R.id.tv_time_add);
tvTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_TIME);
}
});
btn_add_ex = (Button) findViewById(R.id.btn_add_exercise);
list = (ListView) findViewById(R.id.list_excercise);
excercise_list = new ArrayList<ExcerciseModel>();
Log.d("onCreate", "Work!");
adapter = new ExcerciseAdapter(excercise_list, this);
btn_add_ex.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExcercisesFragment dlg = new ExcercisesFragment();
dlg.show(getSupportFragmentManager(),"dlg");
}
});
}
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_TIME) {
Calendar c = Calendar.getInstance();
myHour = c.getTime().getHours();
myMinute = c.getTime().getMinutes();
TimePickerDialog tpd = new TimePickerDialog(this, myCallBack, myHour, myMinute, true);
return tpd;
}
return super.onCreateDialog(id);
}
TimePickerDialog.OnTimeSetListener myCallBack = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
myHour = hourOfDay;
myMinute = minute;
if (myMinute < 10) {
tvTime.setText(myHour + " : 0" + myMinute );
} else {
tvTime.setText(myHour + " : " + myMinute );
}
Log.d("TIME", "minutes " + myMinute);
}
};
#Override
public void onExcerciseAdd(ExcerciseModel model) {
Log.d("Adapter", "null? " + (adapter.isEmpty()));
excercise_list.add(model);
if (adapter.isEmpty()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetInvalidated();
adapter.notifyDataSetChanged();
list.invalidate();
list.invalidateViews();
}
});
}
list.setAdapter(adapter);
for (int i = 0; i < excercise_list.size(); i++){
Log.d("List_ex", "list(" + i +"): " + excercise_list.get(i).getTitle().toString());
}
}
}
Dialogfragment:
public class ExcercisesFragment extends DialogFragment {
private Button btn_add_dialog;
private EditText edit_time;
private EditText edit_count1;
private EditText edit_count2;
private EditText edit_weight;
private AutoCompleteTextView edit_ex;
public interface onButtonAdd {
void onExcerciseAdd (ExcerciseModel model);
}
onButtonAdd button_add;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Title!");
View v = inflater.inflate(R.layout.fragment_add_excersise, null);
btn_add_dialog = (Button) v.findViewById(R.id.btn_add_exercise_fr);
edit_time = (EditText) v.findViewById(R.id.edit_ex_go);
edit_count1 = (EditText) v.findViewById(R.id.edit_podh);
edit_count2 = (EditText) v.findViewById(R.id.edit_repeat);
edit_weight = (EditText) v.findViewById(R.id.edit_weight_add);
edit_ex = (AutoCompleteTextView) v.findViewById(R.id.excercise_title);
button_add = (onButtonAdd) getActivity();
Resources res = getResources();
String[] excersices = res.getStringArray(R.array.excersices);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
R.layout.profile_item, R.id.item_autotext, excersices);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
edit_ex.setAdapter(adapter);
edit_ex.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return false;
}
});
edit_ex.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_ex.showDropDown();
}
});
btn_add_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = edit_time.getText().toString();
String title = edit_ex.getText().toString();
String weight = edit_weight.getText().toString();
String count1 = edit_count1.getText().toString();
String count2 = edit_count2.getText().toString();
if (title.equals("") || count1.equals("") || count2.equals("") || weight.equals("") || time.equals("")) {
Toast.makeText(getActivity(),"Необходимо заполнить все поля", Toast.LENGTH_SHORT).show();
} else {
ExcerciseModel model = new ExcerciseModel();
model.setTitle(edit_ex.getText().toString());
model.setTime(Integer.parseInt(edit_time.getText().toString()));
model.setPodh(Integer.parseInt(edit_count1.getText().toString()));
model.setCount(Integer.parseInt(edit_count2.getText().toString()));
model.setWeight(Integer.parseInt(edit_weight.getText().toString()));
button_add.onExcerciseAdd(model);
dismiss();
}
}
});
return v;
}
}
and Adapter:
public class ExcerciseAdapter extends BaseAdapter {
ArrayList<ExcerciseModel> list;
Activity context;
public ExcerciseAdapter (ArrayList<ExcerciseModel> list, Activity context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewTime;
TextView txtViewPodh;
TextView txtViewCount;
TextView txtViewWeight;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
Log.d("ConvertView", "convertview is null " + (convertView == null));
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_ex, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_adapter_title);
holder.txtViewTime = (TextView) convertView.findViewById(R.id.tv_adapter_time_get);
holder.txtViewPodh = (TextView) convertView.findViewById(R.id.tv_adapter_podh_get);
holder.txtViewCount = (TextView) convertView.findViewById(R.id.tv_adapter_count_get);
holder.txtViewWeight = (TextView) convertView.findViewById(R.id.tv_adapter_weight_get);
holder.txtViewTitle.setText(list.get(position).getTitle().toString());
holder.txtViewTime.setText(String.valueOf(list.get(position).getTime()));
holder.txtViewPodh.setText(String.valueOf(list.get(position).getPodh()));
holder.txtViewCount.setText(String.valueOf(list.get(position).getCount()));
holder.txtViewWeight.setText(String.valueOf(list.get(position).getWeight()));
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Adapter", "List_size = " +list.size());
Log.d("Adapter", "Title(" + position + "): " + list.get(position).getTitle().toString());
return convertView;
}
}
I don't know, but Adatper calls too many times, when I add one element it's calls 3 times. Please help me with this problem.

You only update your list items when you are creating them. You should do something like this:
LayoutInflater inflater = context.getLayoutInflater();
View view = (convertView == null)? inflater.inflate(R.layout.list_item_ex, parent, false) : convertView;
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_adapter_title);
holder.txtViewTime = (TextView) convertView.findViewById(R.id.tv_adapter_time_get);
holder.txtViewPodh = (TextView) convertView.findViewById(R.id.tv_adapter_podh_get);
holder.txtViewCount = (TextView) convertView.findViewById(R.id.tv_adapter_count_get);
holder.txtViewWeight = (TextView) convertView.findViewById(R.id.tv_adapter_weight_get);
holder.txtViewTitle.setText(list.get(position).getTitle().toString());
holder.txtViewTime.setText(String.valueOf(list.get(position).getTime()));
holder.txtViewPodh.setText(String.valueOf(list.get(position).getPodh()));
holder.txtViewCount.setText(String.valueOf(list.get(position).getCount()));
holder.txtViewWeight.setText(String.valueOf(list.get(position).getWeight()));
return view;
Also you don't need to call all of these methods when changing the data set
adapter.notifyDataSetInvalidated();
adapter.notifyDataSetChanged();
list.invalidate();
list.invalidateViews();
Calling adapter.notifyDataSetChanged(); should be enough
You also don't need to reset the adapter every time you change the data, so this line can also be removed
list.setAdapter(adapter);

Related

Display no. of items of a recyclerview in a textview in android studio

I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;

cant Get Original Index from Filtered list view

I have a listview and an editText to filter data. It filters data correctly but e.g, if I filter list and open filtered item it shows me the data of item which was at index 0 of original list not that of filtered item.
My Adapter class:
public class Patient_Adapter extends BaseAdapter implements Filterable{
Activity context;
String[] name, age, number, dip_rate;
//for filtering use arraylists
LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<ArrayList_get_set> arrayList;
private ArrayList<ArrayList_get_set> StringFilterList;
public Patient_Adapter(Activity applicationContext, ArrayList<ArrayList_get_set> arrayList) {
this.context = applicationContext;
/////
this.arrayList = arrayList;
StringFilterList = arrayList;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView name_
,date_
,number_
,dip_rate_
,tv_request_number;
Button button;
}
#Override
public View getView(final int position, View view, final ViewGroup viewGroup) {
Viewholder viewholder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null){
viewholder = new Viewholder();
view = inflater.inflate(R.layout.patient_item_list,null);
viewholder.tv_request_number = (TextView) view.findViewById(R.id.s_req_num);
viewholder.name_ = (TextView) view.findViewById(R.id.name);
viewholder.button = (Button) view.findViewById(R.id.btn_re);
viewholder.date_ = (TextView) view.findViewById(R.id.date);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
viewholder.tv_request_number.setText((arrayList.size()-position)+".");
viewholder.name_.setText(arrayList.get(position).getName());
viewholder.date_.setText(getDate(Long.parseLong(arrayList.get(position).getDate())));
viewholder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView)viewGroup).performItemClick(v,position,1);
}
});
return view;
}
//Filter Results
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
ArrayList<ArrayList_get_set> filterList = new ArrayList<>();
for(int i=0;i<StringFilterList.size();i++){
if((StringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ArrayList_get_set contacts = new ArrayList_get_set();
contacts.setName(StringFilterList.get(i).getName());
contacts.setDate(StringFilterList.get(i).getDate());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=StringFilterList.size();
results.values=StringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<ArrayList_get_set>) results.values;
notifyDataSetChanged();
}
}
This my main activity code
simListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id == 1){
//CUSTOM DIALOG///////////////////////////////
final Dialog dialog = new Dialog(getActivity());
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_re_evaluate);
name_ = (TextView) dialog.findViewById(R.id.name);
f_name_ = (TextView) dialog.findViewById(R.id.f_name);
age_ = (TextView) dialog.findViewById(R.id.age);
number_ = (TextView) dialog.findViewById(R.id.number);
gender_ = (TextView) dialog.findViewById(R.id.gender);
dip_rate_ = (TextView) dialog.findViewById(R.id.dip_rate);
date_ = (TextView) dialog.findViewById(R.id.date);
name_.setText(name[position]);
f_name_.setText(f_name[position]);
age_.setText(age[position]);
number_.setText(number[position]);
dip_rate_.setText(dip_rate[position]);
gender_.setText(gender[position]);
date_.setText(getDate(Long.parseLong(date[position])));
Button re_eval = (Button) dialog.findViewById(R.id.btn);
Button btn_cross = (Button) dialog.findViewById(R.id.cross);
btn_cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
re_eval.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p_name = name_.getText().toString();
p_f_name = f_name_.getText().toString();
p_age = age_.getText().toString();
p_number = number_.getText().toString();
p_dip_rate = dip_rate_.getText().toString();
p_gender = gender_.getText().toString();
p_date = date_.getText().toString();
//go from one fragment to another
Fragment fragment = null;
//send data to next fragment
Bundle bundle = new Bundle();
bundle.putString("name", p_name);
bundle.putString("f_name", p_f_name);
bundle.putString("age", p_age);
bundle.putString("number", p_number);
bundle.putString("dip_rate", p_dip_rate);
bundle.putString("gender", p_gender);
bundle.putString("date", p_date);
fragment = new Questions();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setArguments(bundle);
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
dialog.dismiss();
}
});
dialog.show();
}
}
});
performing filtering here
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (server_check) {
if (server_response.equals("1")) {
if (name.length > 0) {
patient_adapter = new Patient_Adapter(getActivity(),
arrayList);
simListView.setAdapter(patient_adapter);
//filtering data
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
patient_adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});

changes intended on one row but effects are showing in next row

hi friends i am not able to understand how to set text in the same row of the list view where i am having two button with text view at the center but when i am trying to increment or decrement the effect is showing on the next row but not the row on which i want the changes to be applied
CartAdapter.java
public class Cart_Adapter extends BaseAdapter {
Context cartcontext;
List<MobiData> cartlist;
LayoutInflater inflater;
cartlist cartdata;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
CustomButtonListener customButtonListener;
public Cart_Adapter(Context cartcontext, List<MobiData> cartlist) {
this.cartcontext = cartcontext;
this.cartlist = cartlist;
}
#Override
public int getCount() {
return cartlist.size();
}
#Override
public Object getItem(int position) {
return cartlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) cartcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
cartdata = new cartlist();
convertView = inflater.inflate(R.layout.cart_row, parent, false);
cartdata.decrement = (TextView) convertView.findViewById(R.id.decrement);
cartdata.single = (TextView) convertView.findViewById(R.id.single);
cartdata.single.setTag(position);
cartdata.increment = (TextView) convertView.findViewById(R.id.increment);
cartdata.increment.setTag(position);
cartdata.cancel = (TextView) convertView.findViewById(R.id.cancel);
cartdata.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
cartdata.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
cartdata.decrement.setTypeface(carttext);
cartdata.increment.setTypeface(carttext);
cartdata.cancel.setTypeface(carttext);
convertView.setTag(cartdata);
} else {
cartdata = (cartlist) convertView.getTag();
}
MobiData newcart = cartlist.get(position);
cartdata.vcmedname.setText(newcart.getVcmedname());
cartdata.vcmedprice.setText(newcart.getVcmedprice());
cartdata.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
cartdata.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
cartdata.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (customButtonListener !=null){
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
SharedPreferences viewpref = cartcontext.getSharedPreferences("datapref", Context.MODE_PRIVATE);
String cartuid = viewpref.getString("uid", "");
String carttempid = viewpref.getString("tempid", "");
String incremnturl = "http://sampletemplates.net/mobichemist/json/cart_process.php?mid=" + cartids + "&userid=" + cartuid + "&tempid=" + carttempid;
Log.d("Incremnturl", incremnturl);
JsonArrayRequest incrementarray = new JsonArrayRequest(Request.Method.GET, incremnturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject incrobj = response.getJSONObject(i);
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Incrementurl", String.valueOf(error));
}
});
incrementarray.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(incrementarray);
}
});
cartdata.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(cartdata.single.getText().toString());
i--;
if (i <= 0) {
Toast.makeText(Single_Cart_Page.this, "Minimum Quantity is 1", Toast.LENGTH_SHORT).show();
} else {
cartdata.single.setText(String.valueOf(i));
}
}
});
return convertView;
}
static class cartlist {
TextView decrement, single, increment, cancel, vcmedname, vcmedprice;
}
try this and add your other code.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.cart_row, parent, false);
holder = new ViewHolder();
holder.decrement = (TextView) convertView.findViewById(R.id.decrement);
holder.single = (TextView) convertView.findViewById(R.id.single);
holder.increment = (TextView) convertView.findViewById(R.id.increment);
holder.cancel = (TextView) convertView.findViewById(R.id.cancel);
holder.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
holder.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
holder.decrement.setTypeface(carttext);
holder.increment.setTypeface(carttext);
holder.cancel.setTypeface(carttext);
MobiData newcart = cartlist.get(position);
holder.vcmedname.setText(newcart.getVcmedname());
holder.vcmedprice.setText(newcart.getVcmedprice());
holder.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
holder.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
static class ViewHolder {
private TextView decrement;
private TextView single;
private TextView increment;
private TextView vcmedname;
private TextView vcmedprice;
}
Use ArrayAdaper instead of Base Adapter with ViewHolder. Don't set setTag(position) manually for all views.
Find ViewHolder example here https://dzone.com/articles/optimizing-your-listview .It will solve your indexing problem. ViewHolder class sets all views position. Also find more description on Hold View Objects in a View Holder

list view adapter setting null object on custom dialog

hi friends i had tried to implement list view in the custom dialog and passing data dynamically by using JSON and searched everywhere but don't got any solution i had tried everything from past 3 days and also i don't see any wrong in my code too i had set adapter correctly i am getting this error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
public class Cat_comment_adap extends BaseAdapter {
String cid;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int idddget;
private LayoutInflater inflater;
private List<CurrentList> catlist;
private PopupWindow commentWindow;
ArrayList<CurrentList> commentlist = new ArrayList<CurrentList>();
Activity activity;
public Cat_comment_adap(Activity activity, List<CurrentList> catlist) {
this.activity = activity;
this.catlist = catlist;
}
#Override
public int getCount() {
return catlist.size();
}
#Override
public Object getItem(int i) {
return catlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.cat_row, viewGroup, false);
NetworkImageView singleimg = (NetworkImageView) view.findViewById(R.id.singleimg);
final ImageView agree = (ImageView) view.findViewById(R.id.agree);
ImageView commentbox = (ImageView) view.findViewById(R.id.commentbox);
commentbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
});
final CurrentList catertlist = catlist.get(i);
singleimg.setImageUrl(catertlist.getCatimg(), imageLoader);
idddget = catertlist.getCcids();
SharedPreferences eveid = activity.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
cid = eveid.getString("userid", "");
agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android";
Log.d("Vote", "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android");
JsonObjectRequest voting = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String votings = response.getString("status");
if (votings.equals("success")) {
agree.setImageResource(R.drawable.agreed);
Toast.makeText(activity, "Voted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Already Voted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(voting);
}
});
return view;
}
public void onShowpopup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
// commentAdapter = new comment_adapter(activity, commentlist);
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commentWindow = new PopupWindow(popupview, width - 50, height - 400, true);
commentWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.comment_bg));
commentWindow.setFocusable(true);
commentWindow.setOutsideTouchable(true);
commentWindow.showAtLocation(v, Gravity.BOTTOM, 0, 100);
commentsListView.setAdapter(new comment_adapter(activity,commentlist));
commentAdapter.notifyDataSetChanged();
}
Adapter class
public class comment_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CurrentList> commentlist;
public comment_adapter(Activity activity, List<CurrentList> commentlist){
this.activity = activity;
this.commentlist = commentlist;
}
#Override
public int getCount() {
return commentlist.size();
}
#Override
public Object getItem(int i) {
return commentlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.comment_row, viewGroup, false);
TextView user_name = (TextView) view.findViewById(R.id.user_name);
TextView posttime = (TextView) view.findViewById(R.id.posttime);
TextView comtsdetails = (TextView) view.findViewById(R.id.comtsdetails);
CurrentList listofcomments = commentlist.get(i);
user_name.setText(listofcomments.getEvtusername());
posttime.setText(listofcomments.getTimetaken());
comtsdetails.setText(listofcomments.getEvcomment());
return view;
}
}
here in this class Cat_comment_adap in the method onShowpopup change
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
to
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) popupview.findViewById(R.id.commentsListView);
because your inflating listview from this layout so u have to give the name of inflated layout object there not the parameter of the method
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
Here passed view is not R.layout.cat_row as you think but it's a button that was clicked.
So just use onShowpopup(self.view) and it will work :)
or change to onClick(View clickedButton)

Selected list item background colour unexpectedly reused after list scroll on tablets

For my list view on tablets, I'm trying to get my selected list item selection to keep its state when selected but unfortunately I'm seeing some weird behaviour. For some reason whenever I scroll through the list to the point where the selected item is not visible and then scroll back to the point where the selected item IS visible, the background colour unexpectedly gets reused. I believe something needs to go in the getView method but I'm not sure what to do with this method. What must be done in order to prevent the background colour from being reused?
Adapter class
public class VictoriaListAdapter extends BaseAdapter {
private List<Victoria> mData;
private LayoutInflater mInflater;
public VictoriaListAdapter (List<Victoria> data, Context context) {
mData = data;
mData = new ArrayList(mData);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position).getStation();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_dualline, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_station);
holder.description = (TextView) convertView.findViewById(R.id.item_zone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(mData.get(position).getStation());
holder.description.setText(mData.get(position).getZone());
return convertView;
}
/**
* View holder
*/
static class ViewHolder {
private TextView title;
private TextView description;
}
}
Fragment class
public class FragmentVictoriaLine extends ListFragment {
private VictoriaListAdapter mAdapter;
public FragmentVictoriaLine() {
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
public boolean mTwoPane;
public static FragmentVictoriaLine newInstance() {
return new FragmentVictoriaLine();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_victoria_line, container, false);
initialize();
return view;
}
List<Victoria> list = new ArrayList<>();
private void initialize() {
String[] items = getActivity().getResources().getStringArray(R.array.victoria_stations);
String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.victoria_zones);
for (int n = 0; n < items.length; n++){
Victoria victoria = new Victoria();
victoria.setID();
victoria.setStation(items[n]);
victoria.setZone(itemDescriptions[n]);
list.add(victoria);
}
mAdapter = new VictoriaListAdapter(list, getActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
mTwoPane = getActivity().findViewById(R.id.detail_container) != null;
assert v != null;
ListView lv = (ListView)v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private Victoria selectedMain;
private View selectedView;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
VictoriaListAdapter adapter = (VictoriaListAdapter) parent.getAdapter();
String station = adapter.getItem(position);
if (mTwoPane) {
setItemNormal();
View rowView = view;
setItemSelected(rowView);
Fragment newFragment;
if (station.equals(view.getResources().getString(R.string.bho))) {
newFragment = new FragmentVictoriaBHO();
} else if (station.equals(view.getResources().getString(R.string.brx))) {
newFragment = new FragmentVictoriaBRX();
} else if (station.equals(view.getResources().getString(R.string.eus))) {
newFragment = new FragmentVictoriaEUS();
} else if (station.equals(view.getResources().getString(R.string.fpk))) {
newFragment = new FragmentVictoriaFPK();
} else if (station.equals(view.getResources().getString(R.string.green_park))) {
newFragment = new FragmentVictoriaGreenPark();
} else if (station.equals(view.getResources().getString(R.string.hhy))) {
newFragment = new FragmentVictoriaHHY();
} else if (station.equals(view.getResources().getString(R.string.kxsp))) {
newFragment = new FragmentVictoriaKXSP();
} else {
newFragment = new FragmentVictoriaBHO();
}
VictoriaLineActivity activity = (VictoriaLineActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fade_out, R.anim.fade_in);
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (station.equals(view.getResources().getString(R.string.bho))) {
intent = new Intent(getActivity(), VictoriaBHOActivity.class);
} else if (station.equals(view.getResources().getString(R.string.brx))) {
intent = new Intent(getActivity(), VictoriaBRXActivity.class);
} else if (station.equals(view.getResources().getString(R.string.eus))) {
intent = new Intent(getActivity(), VictoriaEUSActivity.class);
} else if (station.equals(view.getResources().getString(R.string.fpk))) {
intent = new Intent(getActivity(), VictoriaFPKActivity.class);
} else if (station.equals(view.getResources().getString(R.string.green_park))) {
intent = new Intent(getActivity(), VictoriaGreenParkActivity.class);
} else if (station.equals(view.getResources().getString(R.string.hhy))) {
intent = new Intent(getActivity(), VictoriaHHYActivity.class);
} else if (station.equals(view.getResources().getString(R.string.kxsp))) {
intent = new Intent(getActivity(), VictoriaKXSPActivity.class);
} else {
intent = new Intent(getActivity(), VictoriaBHOActivity.class);
}
startActivity(intent);
}
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#868F98"));
TextView tv0 = (TextView) rowView.findViewById(R.id.item_station);
tv0.setTextColor(Color.WHITE);
TextView tv1 = (TextView) rowView.findViewById(R.id.item_zone);
tv1.setTextColor(Color.WHITE);
}
public void setItemNormal() {
for (int i = 0; i < getListView().getChildCount(); i++) {
View v = getListView().getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
super.onActivityCreated(savedInstanceState);
}
}
data class
public class Victoria {
public Victoria(){}
private String station;
private String zone;
private boolean selected;
public String getStation(){
return station;
}
public void setStation(String item){
this.station = item;
}
public String getZone(){
return zone;
}
public void setZone(String zone){
this.zone = zone;
}
private int _id;
public void getID(int _id){
this._id = _id;
}
public int setID(){
return _id;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
When you scroll through the list, the items/views in the ListView will get reused to optimize the memory.So when you set a selected state to a list item, you will see that selected state in multiple list items as you scroll through. The best way to prevent this is to preserve the state in your Data Model and set the state in getView function of the Adapter.
Here is what you can do -
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
VictoriaListAdapter adapter = (VictoriaListAdapter) parent.getAdapter();
//reverse the selected state in data model
for (int i = 0; i < adapter.getCount(); i++) {
Victoria victoria = (Victoria)adapter.getItem(i);
victoria.setSelected(i == position ? true : false);
}
Victoria victoria = (Victoria)adapter.getItem(position);
---
---
And in adapter -
#Override
public Object getItem(int position) {
//Return full object, coz we need to access other
//member variables too
return mData.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_dualline, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_station);
holder.description = (TextView) convertView.findViewById(R.id.item_zone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Victoria victoria = (Victoria)getItem(position);
holder.title.setText(victoria.getStation());
holder.description.setText(victoria.getZone());
if (victoria.isSelected()) {
setItemSelected(convertView);
} else {
setItemNormal(convertView);
}
return convertView;
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#868F98"));
TextView tv0 = (TextView) rowView.findViewById(R.id.item_station);
tv0.setTextColor(Color.WHITE);
TextView tv1 = (TextView) rowView.findViewById(R.id.item_zone);
tv1.setTextColor(Color.WHITE);
}
public void setItemNormal(View v) {
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
Hope it helps!

Categories