NullPointer cause in CustomListview - java

I am developing an application in which i have Implement CustomListview with one icon, raitingbar,checkbox. now everything is display fine but when i have insert one button it getting me nullpointer error.i know that nullpointer error cause in situation of not initialize the control... but i have tried so far and not understand what is the proble over here....
i have take one viewHold for declare all Row item..
package com.AppFavorits;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
class ViewHolder {
public ImageView imgvFavrowiconappicon;
public TextView txvxFavrowiconappname;
public RatingBar ratingBar1;
public CheckBox chkbxFavrowsel;
public Button btnFavrowOpen;
ViewHolder(View base) {
this.ratingBar1=(RatingBar)base.findViewById(R.id.ratingBar1);
this.ratingBar1.setFocusable(false);
this.txvxFavrowiconappname=(TextView)base.findViewById(R.id.txvxFavrowiconappname);
this.imgvFavrowiconappicon=(ImageView)base.findViewById(R.id.imgvFavrowiconappicon);
this.chkbxFavrowsel = (CheckBox)base.findViewById(R.id.chkbxFavrowsel);
this.btnFavrowOpen= (Button)base.findViewWithTag(R.id.btnFavrowOpen);
this.chkbxFavrowsel.setFocusable(false);
}
}
CustomAdapter
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.rowfavorites,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
flFavRate[position] = rating;
// stored listitem rating in array
datasource.open();
datasource.UpdateRating(String.valueOf(rating), String.valueOf(position+1));
datasource.close();
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
boolean bAlreadyfav = false;
String prefixlink = "https://play.google.com/store/apps/details?id=";
ShrdDatasource.open();
ArrayList<Comment> alDSPackagenm = ShrdDatasource.getAllPackage();
ArrayList<Comment> alDSRating = ShrdDatasource.getAllRating();
ArrayList<Comment> alDSID = ShrdDatasource.getID();
Log.i(TAG, "First Package cmp"+ alDSPackagenm);
ShrdDatasource.close();
int i = 0 ;
if (alDSPackagenm != null) {
for (i = 0; i < alDSPackagenm.size(); i++) {
if(alDSPackagenm.get(i).toString().equalsIgnoreCase(prefixlink + alPackagenm.get(position).toString() + "1x2optrue") || alDSPackagenm.get(i).toString().equalsIgnoreCase(prefixlink + alPackagenm.get(position).toString() + "1x2opfalse"))
{
bAlreadyfav = true;
break;
}
}
}
GolbPosition = position;
if (bAlreadyfav == true) {
Log.i(TAG, "Share positionis "+i);
Log.i(TAG, "Current positionis "+position);
Log.i(TAG,"ShrdDatasource Rating" + alDSRating.get(i).toString());
Log.i(TAG,"Favorite Rating" + String.valueOf(flFavRate[GolbPosition]));
if(alDSRating.get(i).toString().equalsIgnoreCase(String.valueOf(flFavRate[GolbPosition])))
{
Toast.makeText(getBaseContext(), " App already in Share list ",
Toast.LENGTH_LONG).show();
}
else
{
//alid
/*GolbPosition = position;
new GETFavTask().execute();*/
//UpdateRating
ShrdDatasource.open();
ShrdDatasource.UpdateRating(String.valueOf(flFavRate[GolbPosition]), alDSID.get(i).toString());
ShrdDatasource.close();
//Update Query fire
}
} else {
//Log.i(TAG, "First Package cmp"+ alDSPackagenm.get(position).toString());
Log.i(TAG, "Second Package cmp"+ alPackagenm.get(position).toString());
GolbPosition = position;
new GETFavTask().execute();
// add item in Database when user get select
}
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
//holder.btnFavrowOpen.setTag(mlist.get(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(drblAlIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.btnFavrowOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// OpenApp(alPackagenm.get(position).toString());
}
});
try
{
if (alAppRating.get(position) == null | alAppRating.get(position).toString().equalsIgnoreCase("null")) {
holder.ratingBar1.setRating(0.0f);
} else {
holder.ratingBar1.setRating(Float.parseFloat(alAppRating
.get(position).toString()));
}
}catch (Exception e) {
e.printStackTrace();
}
//holder.ratingBar1.setRating(Float.parseFloat(alAppRating.get(position).toString()));
return (row);
}
Here you can see the button holder.btnFavrowOpen with onclicklistner i got null pointer at that line very much tied what happen here.... if i am remove button code in adapter it getting work fine...but when i write button code again it getting Error of null pointer

use
base.findViewById
and not
base.findViewWithTag

Related

How to use holder.todoCheckbox.setChecked? RecyclerView

How to use holder.todoCheckbox.setChecked (todoBool);
I have a recycler view that contains 3 view holders.
I have got a MainActivity, HeaderFooterAdapter, SimpleItamAdapter.
I have the logic when I click on a checkbox that the list will filter. In the setOnCheckedChangeListener I set the variables todoBool, doneBool, projectBool to the new truth values.
Then I would like to set the checkboxes to true or false depending on these values.
The problem occurs on this line of code
holder.todoCheckbox.setChecked(todoBool);
This causes a crash in the app.
public void onBindHeaderItemViewHolder(#NonNull HeaderViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
//This following 3 lines causes error. how to manage this?
holder.todoCheckbox.setChecked(todoBool);
holder.doneCheckbox.setChecked(doneBool);
holder.projektCheckbox.setChecked(projectBool);
holder.todoCheckbox.setOnCheckedChangeListener(…); //here i set to Bools
holder.doneCheckbox.setOnCheckedChangeListener(…);
holder.projektCheckbox.setOnCheckedChangeListener(…);
}
I tried that. Also causes crash in the app.
holder.todoCheckbox.setChecked(false);
holder.doneCheckbox.setChecked(false);
holder.projektCheckbox.setChecked(false);
What do i do wrong?
I pushed everythink here. The "localBranch" is the not working one. The "devMaster" works. https://github.com/SaschaGolod/T09b.10-Exercise-AddViewModelToAddTaskActivity
Many thanks if someone can help me here
Here is my whole adapter class:
package com.example.android.todolist.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import com.example.android.todolist.R;
import com.h6ah4i.android.widget.advrecyclerview.utils.RecyclerViewAdapterUtils;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import static com.example.android.todolist.MainActivity.onItemClickedDefault;
import static com.example.android.todolist.MainActivity.onItemClickedDone;
import static com.example.android.todolist.MainActivity.onItemClickedProject;
import static com.example.android.todolist.MainActivity.onItemClickedTodo;
public class DemoHeaderFooterAdapter
extends AbstractHeaderFooterWrapperAdapter<DemoHeaderFooterAdapter.HeaderViewHolder, DemoHeaderFooterAdapter.FooterViewHolder>
implements View.OnClickListener {
private static final String TAG = "DemoHeaderFooterAdapter";
private OnListItemClickMessageListener mOnItemClickListener;
private Context mContext;
private boolean todoBool = false;
private boolean doneBool = false;
private boolean projectBool = false;
static class HeaderViewHolder extends RecyclerView.ViewHolder {
private CheckBox todoCheckbox;
private CheckBox doneCheckbox;
private CheckBox projektCheckbox;
HeaderViewHolder(View itemView) {
super(itemView);
todoCheckbox = itemView.findViewById(R.id.todoCheckboxID);
doneCheckbox = itemView.findViewById(R.id.doneCheckboxID);
projektCheckbox = itemView.findViewById(R.id.projektCheckboxID);
Log.i(TAG, "onCreate finished");
}
}
static class FooterViewHolder extends RecyclerView.ViewHolder {
FooterViewHolder(View itemView) {
super(itemView);
}
}
public DemoHeaderFooterAdapter(RecyclerView.Adapter adapter, OnListItemClickMessageListener clickListener, Context mContext) {
Log.i(TAG, "DemoHeaderFooterAdapter");
setAdapter(adapter);
mOnItemClickListener = clickListener;
this.mContext = mContext;
}
#Override
public int getHeaderItemCount() {
return 1;
}
#Override
public int getFooterItemCount() {
return 1;
}
#NonNull
#Override
public HeaderViewHolder onCreateHeaderItemViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.i(TAG, "HeaderViewHolder");
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_item, parent, false);
HeaderViewHolder vh = new HeaderViewHolder(v);
if (mOnItemClickListener != null) {
vh.itemView.setOnClickListener(this);
}
return vh;
}
#NonNull
#Override
public FooterViewHolder onCreateFooterItemViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.footer_item, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
if (mOnItemClickListener != null) {
vh.itemView.setOnClickListener(this);
}
return vh;
}
#Override
public void onClick(#NonNull View v) {
RecyclerView rv = RecyclerViewAdapterUtils.getParentRecyclerView(v);
RecyclerView.ViewHolder vh = rv.findContainingViewHolder(v);
int rootPosition = vh.getAdapterPosition();
if (rootPosition == RecyclerView.NO_POSITION) {
return;
}
// need to determine adapter local position like this:
RecyclerView.Adapter rootAdapter = rv.getAdapter();
int localPosition = WrapperAdapterUtils.unwrapPosition(rootAdapter, this, rootPosition);
// get segment
long segmentedPosition = getSegmentedPosition(localPosition);
int segment = extractSegmentPart(segmentedPosition);
int offset = extractSegmentOffsetPart(segmentedPosition);
String message;
if (segment == SEGMENT_TYPE_HEADER) {
message = "CLICKED: Header item " + offset;
} else if (segment == SEGMENT_TYPE_FOOTER) {
message = "CLICKED: Footer item " + offset;
} else {
throw new IllegalStateException("Something wrong.");
}
mOnItemClickListener.onItemClicked(message);
}
// --------------------------------------------
// [ OPTIONAL ]
// Set full-span for Grid layout and Staggered Grid layout
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
setupFullSpanForGridLayoutManager(recyclerView);
}
#Override
public void onBindHeaderItemViewHolder(#NonNull HeaderViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
//Maybe here is the mistake?
//Reload State of SharedPreferences
//This following 3 lines causes error :| how to manage this?
holder.todoCheckbox.setChecked(false);
holder.doneCheckbox.setChecked(false);
holder.projektCheckbox.setChecked(false);
holder.todoCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = false;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDefault);
}else{
todoBool = true;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedTodo);
}
}
});
holder.doneCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = false;
doneBool = true;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDone);
}else{
todoBool = false;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDefault);
}
}
});
holder.projektCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = true;
doneBool = false;
projectBool = true;
mOnItemClickListener.onItemClicked(onItemClickedProject);
}else{
todoBool = true;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedTodo);
}
}
});
}
#Override
public void onBindFooterItemViewHolder(#NonNull FooterViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
}
// Filling span for GridLayoutManager
private void setupFullSpanForGridLayoutManager(RecyclerView recyclerView) {
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
if (!(lm instanceof GridLayoutManager)) {
return;
}
final GridLayoutManager glm = (GridLayoutManager) lm;
final GridLayoutManager.SpanSizeLookup origSizeLookup = glm.getSpanSizeLookup();
final int spanCount = glm.getSpanCount();
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
final long segmentedPosition = getSegmentedPosition(position);
final int segment = extractSegmentPart(segmentedPosition);
final int offset = extractSegmentOffsetPart(segmentedPosition);
if (segment == SEGMENT_TYPE_NORMAL) {
return origSizeLookup.getSpanSize(offset);
} else {
return spanCount; // header or footer
}
}
});
}
private void applyFullSpanForStaggeredGridLayoutManager(RecyclerView.ViewHolder holder) {
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
// Filling span for StaggeredGridLayoutManager
if (lp instanceof StaggeredGridLayoutManager.LayoutParams) {
((StaggeredGridLayoutManager.LayoutParams) lp).setFullSpan(true);
}
}
// --------------------------------------------
}
-----------Edit 3----------------
public void notifyTaskEntrysChanged(String message){
switch (message) {
//Here set Booleans
}
filteredTaskEntries.clear();
//Now fill the filteredTaskEntries with new TaskEntries depending on the bools
Log.d(TAG, "notifyDataSetChanged next Step");
notifyDataSetChanged(); //Error 1. Line in Logcat
}
------------Edit2-----------------
In the MainActifity i handle the clicks like this:
#Override
public void onItemClicked(String message) {
switch (message) {
case onItemClickedTodo:
Log.d(TAG, "onItemClickedTriggerd: TodoChecked true");
TodoChecked = true;
DoneChecked = false;
ProjectChecked = false;
break;
case onItemClickedDone:
TodoChecked = false;
DoneChecked = true;
ProjectChecked = false;
break;
case onItemClickedProject:
ProjectChecked = true;
TodoChecked = true;
DoneChecked = false;
break;
default:
ProjectChecked = false;
TodoChecked = false;
DoneChecked = false;
break;
}
saveStateOfButtons();
Log.d(TAG, "mFilteringAdapter.notifyTaskEntrysChanged(message)");
mFilteringAdapter.notifyTaskEntrysChanged(message); //Error 2. Line in Logcat
}
The 3. Line Error is this code:
mOnItemClickListener.onItemClicked(onItemClickedDefault);
------------Edit1-----------------
Here is the Log.
[...]
D/DemoHeaderFooterAdapter: ----------------------------------------------------
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/DemoHeaderFooterAdapter: TodoSetOnCheckedChangeListener triggerd
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/MainActivity: onItemClickedTriggerd: TodoChecked true
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/MainActivity: saveStateButtons
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/MainActivity: mFilteringAdapter.notifyTaskEntrysChanged(message)
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/SimpleDemoItemAdapter: notifyTaskEntrysChanged finished
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/SimpleDemoItemAdapter: notifyDataSetChanged next Step
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/AndroidRuntime: Shutting down VM
03-22 19:50:49.277 13331-13331/com.example.android.todoDB E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.todoDB, PID: 13331
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling androidx.recyclerview.widget.RecyclerView{e9fff59 VFED..... .F....ID 0,0-480,680 #7f090090 app:id/recycler_view}, adapter:com.example.android.todolist.adapters.DemoHeaderFooterAdapter#1c3071e, layout:androidx.recyclerview.widget.LinearLayoutManager#b695bff, context:com.example.android.todolist.MainActivity#755b94c
at androidx.recyclerview.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:2880)
at [...]
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11997)
at androidx.recyclerview.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:7070)
at com.example.android.todolist.adapters.SimpleDemoItemAdapter.notifyTaskEntrysChanged(SimpleDemoItemAdapter.java:287)

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

multiple checkbox, indexOutOfBounds in a custom adapter with listview

I am trying to handle multiple checkboxes in order to delete or edit elements from a list, the list has custom adapter with its custom layout, inside this layout I am creating the checkbox, however I am getting a IndexOutOfBounds exception when I am trying to evaluate a boolean array even if it has been initialized.
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi)
{
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()]; //this is where I initialize the array
}
and this where i am getting the exception at:
in the adapter
public View getView
this
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
the log in debug window
checked[position]= java.lang.IndexOutOfBoundsException : Invalid array range: 0 to 0
the log in android monitor
03-22 17:18:03.121 2024-3372/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key:
java.io.IOException: Invalid device key response.
at evk.a(:com.google.android.gms:274)
at evk.a(:com.google.android.gms:4238)
at evj.a(:com.google.android.gms:45)
at evd.a(:com.google.android.gms:50)
at evc.a(:com.google.android.gms:104)
at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049)
at ecm.call(:com.google.android.gms:2041)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at llt.run(:com.google.android.gms:450)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at lqc.run(:com.google.android.gms:17)
at java.lang.Thread.run(Thread.java:761)
I put a breakpoint and I can see that the size of myMeasureEvi is not 0, but for some reason, checked is always 0
Any hints on this? if you need more information please let me know
EDIT: Complete adapter code
public class MeasureTableAdapter extends ArrayAdapter<MeasureEvi> {
private final Activity context;
ArrayList<MeasureEvi> myMeasureEvi;
boolean[] checked;
public OnHeadlineSelectedListener mCallback;
public interface OnHeadlineSelectedListener { public void onMeasureInDrawActiom(int position, boolean delete); }
public void setCallback(OnHeadlineSelectedListener mCallback){ this.mCallback = mCallback; }
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi) {
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()];
}
private class ViewHolder {
TextView txtIndex;
EditText txtCoordX;
EditText txtCoordY;
ImageView imgEvidence;
TextView txtEvidence;
TextView txtName;
TextView txtDescription;
CheckBox checkBox;
}
#Override
public View getView(final int position, View rowView, ViewGroup parent){
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if(rowView == null) {
rowView = inflater.inflate(R.layout.adapter_tablamedida_item, null, true);
holder = new ViewHolder();
holder.txtIndex = (TextView) rowView.findViewById(R.id.TxtIndex);
holder.txtCoordX = (EditText) rowView.findViewById(R.id.TxtCoordX);
holder.txtCoordY = (EditText) rowView.findViewById(R.id.TxtCoordY);
holder.imgEvidence = (ImageView) rowView.findViewById(R.id.ImgIcon);
holder.txtEvidence = (TextView) rowView.findViewById(R.id.TxtEvidenciaId);
holder.txtName = (TextView) rowView.findViewById(R.id.TxtCategory);
holder.txtDescription = (TextView) rowView.findViewById(R.id.TxtDescription);
holder.checkBox= (CheckBox) rowView.findViewById(R.id.checkBox);
rowView.setTag(holder);
} else {
holder= (ViewHolder) rowView.getTag();
}
MeasureEvi currentItem = getItem(position);
if (currentItem != null) {
int suma = currentItem.getmOrderIndex()+1;
Evidence myEvidence = DataIpat.evidencetArray.get(currentItem.geteIndex());
holder.checkBox.setChecked(false);
if (holder.txtIndex != null) holder.txtIndex.setText("" + suma );
if (holder.imgEvidence != null) holder.imgEvidence.setImageDrawable(myEvidence.geteImage().getDrawable());
if (holder.txtEvidence != null) holder.txtEvidence.setText("" + myEvidence.geteId());
if (holder.txtName != null) holder.txtName.setText(myEvidence.geteCategory() + " " + (myEvidence.getcIndex() + 1));
if (holder.txtDescription != null) holder.txtDescription.setText(currentItem.getmDescription() + " - " + currentItem.getmObservation());
if (holder.txtCoordX != null) {
holder.txtCoordX.setSelectAllOnFocus(true);
holder.txtCoordX.setText("" + currentItem.getmCoordenate().x);
holder.txtCoordX.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordX.setText("" + coord.x);
}
}
});
}
if (holder.txtCoordY != null){
holder.txtCoordY.setSelectAllOnFocus(true);
holder.txtCoordY.setText("" + currentItem.getmCoordenate().y);
holder.txtCoordY.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordY.setText("" + coord.y);
}
}
});
}
}
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked())
checked[position] = true;
else
checked[position] = false;
}
});
return rowView;
}
private boolean setPosition(String coordX, String coordY, int position){
try {
float X = Float.parseFloat(coordX);
float Y = Float.parseFloat(coordY);
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
if (X != 0 && Y != 0 ) { // Valido que los x y y sean diferentes de cero
if(X != coord.x || Y != coord.y) { // valida que el dato alla cambiado
for(MeasureEvi myMeasure: DataIpat.measureEviArray){ //
if (myMeasure.geteIndex() == DataIpat.measureEviArray.get(position).geteIndex()
&& myMeasure.getmIndex() != DataIpat.measureEviArray.get(position).getmIndex()){
if(X == myMeasure.getmCoordenate().x && Y == myMeasure.getmCoordenate().y) {
Toast.makeText(getContext(), "Error no se permiten coordenadas iguales.", Toast.LENGTH_SHORT).show();
return false;
}
}
}
DataIpat.measureEviArray.get(position).setmCoordenate(new PointF(X, Y));
mCallback.onMeasureInDrawActiom(position, false); // true for delete
}
}
return true;
} catch (Exception ex) {
return false;
}
}
}
By doing a deeper debug at my app, I noticed that the adapter is being initialized way before, so it won´t go trhough the constructor anymore, unless is initialized again, therefore the size of the array will always be 0.
SOLUTION:
As the array ask for the size of itself, I decided to use an ArrayList
create variable to store the checked boxes:
public static ArrayList<MeasureEvi> myChecked = new ArrayList<MeasureEvi>();
create a listener event to store your choices:
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked()) {
myChecked.add(DataIpat.measureEviArray.get(position));
}
else {
myChecked.remove(DataIpat.measureEviArray.get(position));
}
for (int i=0; i<myChecked.size(); i++){
MeasureEvi e= myChecked.get(i);
Log.d("mOrder", String.valueOf(e.getmOrderIndex()));
}
}
});
and KABOOM, now I have the objets from where I checked!

Android BaseAdapter only shows correct information once

I'm trying to put together an adapter that will display the number of occurrences in a list. There are two ListViews in a tab host with each being in its own tab. As long as you do not click on the tab that shows the occurrences it will keep up with the data input just fine. The first time you go to view the listview, all of the groups are displayed with the correct amount of occurrences for each; however, from then on it does not want to update properly. At times it will not update at all, re-insert an existing group but still keep the old one.
For example, if I were to put in 10, 20, and 30 the first time I go to view the groups listview I would see:
10 -- 1
20 -- 1
30 -- 1
...but if I were to put in another 10 it would still display the same thing with no update.
When I put something else in like 45 I get:
10 -- 1
20 -- 1
30 -- 1
10 -- 2
I can keep adding other numbers and it will just keep adding in 10 -- 1's or sometimes even more 20's or 30's. If I use debugAll() in the log window it will show that it attempts all of the numbers that I put in, and it will return the correct number of occurences, just the display won't keep up and is displaying more of what is already there.
I have tried putting in several log statements and they show that the information in the adapter is right, just the display is wrong.
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private final ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) { // FIXME
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
} else {
listView = convertView;
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int newInt = Integer.parseInt(mData.get(oldValue));
if (newInt > 1) {
mData.put(oldValue, String.valueOf(--newInt));
String secondInt = mData.get(newValue);
if (secondInt != null) {
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
mData.put(newValue, "1");
Log.i("Old Value ", oldValue + " Is Gone From HashMap");
}
keyArray.add(0, newValue);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
Log.i("Old Value", oldValue + " Is Gone From HashMap");
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void debugValue (String key) {
Log.i("AdapterDebug Value", key + " has " + mData.get(key));
}
public void debugAll () {
int size = keyArray.size();
for (int i = 0; i < size; i++) {
String retrieve = (String) keyArray.get(i);
Log.i("AdapterDebug All", "Attempted " + retrieve + " and retrieved " + mData.get(retrieve));
}
}
}
EDIT:
I figured some one might find the fully working version useful so I'll put this here.
It will keep track of re occurring values. Build off of it, use it as is, I don't care.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
/*
* ARRAY ADAPTER FOR KEEPING TRACK OF REOCCURRING VALUES AND DISPLAYING ON A LISTVIEW
* CREATED BY : COREY WILLIAMS
* 8/13/2014
*
* BeerWare (http://en.wikipedia.org/wiki/Beerware)
* */
class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
} else {
listView = convertView;
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int oldAmmount = Integer.parseInt(mData.get(oldValue)); // GET HOW MANY ARE LEFT OF WHAT YOU SELECTED
boolean alreadyHasNewValue = mData.containsKey(newValue);
if (oldAmmount > 1) { // IF THERE IS SOME LEFT
mData.put(oldValue, String.valueOf(--oldAmmount));
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
}
if (!keyArray.contains(newValue)) {
keyArray.add(0, newValue);
}
}
this.notifyDataSetChanged();
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
}
this.notifyDataSetChanged();
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
}
public ArrayList getKeys () {
return keyArray;
}
public void restoreKeys (ArrayList<String> restore) {
keyArray = restore;
this.notifyDataSetChanged();
}
public LinkedHashMap<String, String> getValues () {
return mData;
}
public void restoreValues (LinkedHashMap<String, String> restore) {
mData = restore;
this.notifyDataSetChanged();
}
}
In the "getView" method you must update the content placeholders (TextView(s) in your code) even if "convertView" is not null.
It's because of view recycling system of ListView.
So the updated code could be like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
} else {
listView = convertView;
}
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
return listView;
}

Issue with checkbox checked

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Categories