RecyclerView is crashing after fast scrolling and calling API onBindViewHolder - java

public class FragmentPatientsByVital extends Fragment {
private RecyclerView mRecyclerView;
private ArrayList<Patient> mList;
private AdapterVitalPatient mAdapter;
private MultiStateToggleButton mMultiStateToggleButton;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_patient_by_vital, container, false);
initUi(v);
if (mList != null)
updateList(mList);
return v;
}
private void initUi(View v) {
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mMultiStateToggleButton = (MultiStateToggleButton) v.findViewById(R.id.mstb_multi_id);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMultiStateToggleButton.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
#Override
public void onValueChanged(int position) {
mAdapter.filterBy(position);
}
});
}
public void updateList(ArrayList<Patient> mList) {
if (mList == null) return;
this.mList = mList;
if (mAdapter == null)
mAdapter = new AdapterVitalPatient(mList);
mRecyclerView.setAdapter(mAdapter);
}
public static FragmentPatientsByVital newIntance() {
FragmentPatientsByVital f = new FragmentPatientsByVital();
return f;
}
}
Adapter
public class AdapterVitalPatient extends RecyclerView.Adapter<AdapterVitalPatient.ViewHolder> {
private ArrayList<Patient> mList;
public AdapterVitalPatient(ArrayList<Patient> mList) {
this.mList = mList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(InjectUtils.getInflator().inflate(R.layout.adapter_vital_patient, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Patient p = mList.get(position);
holder.mNameTextView.setText(p.getName());
if (mList.get(position).getSummary() != null) {
holder.updateRecords(mList.get(position).getSummary());
} else {
try {
holder.callApi(p.getEmail(), position);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mList.size();
}
public void filterBy(int position) {
switch (position) {
case 0: //!--- Any
break;
case 1: //!--- Normal
break;
case 2: //!--- High
break;
case 3: //!--- Low
break;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mNameTextView;
private final ProgressBar mProgressBar;
private final GridLayout mTableLayout;
public ViewHolder(View itemView) {
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_title);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
mTableLayout = (GridLayout) itemView.findViewById(R.id.table_layout);
}
public void callApi(String email, final int pos) {
try {
RahaDelegates api = InjectUtils.getNetworkObj().create(RahaDelegates.class);
Call<String> call = api.getLatestVitals(String.format(RahaDelegates.GET_LATEST_VITALS, email));
InjectUtils.getNetworkClient().callApi(call, new ApiInterface() {
#Override
public void onResponse(boolean result, String completeResponse) {
Type token = new TypeToken<ArrayList<Vital>>() {
}.getType();
mList.get(getAdapterPosition()).setSummary((ArrayList<Vital>) InjectUtils.getGsonObj().fromJson(completeResponse, token));
updateRecords(mList.get(pos).getSummary());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(String message) {
mProgressBar.setVisibility(View.GONE);
}
});
} catch (Exception e){
e.printStackTrace();
}
}
public void updateRecords(ArrayList<Vital> details) {
mTableLayout.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mTableLayout.removeAllViews();
for (int i = 0; i < details.size(); i++) {
Log.e("List Size", String.valueOf(details.size()));
Vital v = details.get(i);
if (!v.getVitalName().toLowerCase().contains("lungreco") && !v.getVitalName().toLowerCase().contains("kickco")) {
View view = InjectUtils.getInflator().inflate(R.layout.adapter_home_vital_patient, mTableLayout, false);
mTableLayout.addView(view);
TextView name = (TextView) view.findViewById(R.id.vital_name);
TextView value = (TextView) view.findViewById(R.id.vital_value);
name.setText(v.getVitalName());
if (v.getVitalName().toLowerCase().contains("bodyc")) {
value.setText(v.getFat() + "/" + v.getMuscale() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("temp")) {
if (v.getValue() != null) {
value.setText(Math.round(Float.valueOf(v.getValue())) + " " + v.getUnit());
}
} else if (v.getVitalName().toLowerCase().contains("heartra")) {
value.setText(v.getValue());
} else if (v.getVitalName().toLowerCase().contains("etalbe")) {
value.setText(v.getValue() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("bloodpres")) {
value.setText(v.getSystolic() + "/" + v.getDiastolic() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("loodoxy")) {
value.setText(v.getValue() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("oodglucos")) {
value.setText(v.getValue() + " " + v.getUnit());
}
}
}
}
}
}
02-10 09:06:39.430 1600-1600/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
02-10 09:06:39.476 16831-17154/? E/AndroidCll-SettingsSync: Could not get or parse settings
02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.cj: Received server error from request: invalid_api_key
02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.ci: Error occurred while executing Braze request: invalid_api_key
02-10 09:06:39.603 16831-17154/? E/AndroidCll-SettingsSync: Could not get or parse settings
02-10 09:06:39.759 1600-1600/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
02-10 09:06:41.294 16594-16594/sa.digitrends.rahah.doctor E/AndroidRuntime: FATAL EXCEPTION: main
Process: sa.digitrends.rahah.doctor, PID: 16594
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at sa.digitrends.doctor.adapter.AdapterVitalPatient$ViewHolder.updateRecords(AdapterVitalPatient.java:125)
at sa.digitrends.doctor.adapter.AdapterVitalPatient$ViewHolder$1.onResponse(AdapterVitalPatient.java:106)
at sa.app.base.retrofit.client.NetworkClient$1.onResponse(NetworkClient.java:60)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
02-10 09:06:41.761 16831-16831/? E/Referral: (LauncherApplication.java:890) restarted

You can remove below code segment from onBindView and add it inside another method that needs to fire when user do that relevant action
if (mList.get(position).getSummary() != null) {
holder.updateRecords(mList.get(position).getSummary());
} else {
try {
holder.callApi(p.getEmail(), position);
} catch (Exception e) {
e.printStackTrace();
}
}
then you can do notifydatasetchanged after get success response inside that public void onResponse(boolean result, String completeResponse)

It seems you have server error
Appboy v2.5.0 .bo.app.cj: Received server error from request: invalid_api_key 02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.ci: Error occurred while executing Braze request: invalid_api_key 02-10 09:06:39.603 16831-17154

Error is due to NullPointerException
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
Update updateRecords methods as below
public void updateRecords(#Nullable ArrayList<Vital> details) {
mProgressBar.setVisibility(View.GONE);
if(details == null) {
return;
}
. . .
. . .
. . .
}
In general there can be further improvement made.
Avoid making API calls directly from Fragments or any Classes having views
Parse response in background thread. Below code might block your main thread for long time, when response is huge.
InjectUtils.getGsonObj().fromJson(completeResponse, token)

Related

Represent firestore data into List view [duplicate]

I wanted to know how to load more data in recylcer view using firestore.
Query query = FirebaseFirestore.getInstance()
.collection("ie").limit(5);
adapter=new InterviewAdapter(this,query);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Adapter class looks like this:
public class InterviewAdapter extends FireStoreAdapter<InterviewAdapter.ViewHolder> {
public interface OnInterviewSelectedListener {
void onInterviewSelected(DocumentSnapshot interview);
}
private InterviewAdapter.OnInterviewSelectedListener mListener;
public InterviewAdapter(Query query, OnInterviewSelectedListener listener) {
super(query);
mListener = listener;
}
#Override
public InterviewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new InterviewAdapter.ViewHolder(inflater.inflate(R.layout.ie, parent, false));
}
#Override
public void onBindViewHolder(InterviewAdapter.ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title,companyName,username,views,isHired;
public ViewHolder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.title);
companyName= (TextView) itemView.findViewById(R.id.companyName);
username= (TextView) itemView.findViewById(R.id.username);
views= (TextView) itemView.findViewById(R.id.views);
isHired= (TextView) itemView.findViewById(R.id.isHired);
}
public void bind(final DocumentSnapshot snapshot,
final OnInterviewSelectedListener listener) {
InterviewExperience experience;
String companyName=snapshot.getString("companyName");
boolean isHired=Boolean.valueOf(snapshot.getBoolean("isHired"));
String username=snapshot.getString("username");
long views=new Double(Double.valueOf(snapshot.getDouble("views"))).longValue();
String id=snapshot.getId();
String title=snapshot.getString("title");
experience=new InterviewExperience(id,title,companyName,username,isHired,views,null,null);
this.title.setText(experience.getTitle());
this.companyName.setText("Company Name: "+experience.getCompanyName());
this.isHired.setText("Hired: "+experience.isHired());
this.views.setText("Views: "+experience.getViews()+"");
this.username.setText("Created By: "+experience.getUsername());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onInterviewSelected(snapshot);
}
}
});
}
}
}
public abstract class FireStoreAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH>
implements EventListener<QuerySnapshot> {
private static final String TAG = "FirestoreAdapter";
private Query mQuery;
private ListenerRegistration mRegistration;
private ArrayList<DocumentSnapshot> mSnapshots = new ArrayList<>();
public FireStoreAdapter(Query query) {
mQuery = query;
}
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "onEvent:error", e);
onError(e);
return;
}
// Dispatch the event
Log.d(TAG, "onEvent:numChanges:" + documentSnapshots.getDocumentChanges().size());
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
switch (change.getType()) {
case ADDED:
onDocumentAdded(change);
break;
case MODIFIED:
onDocumentModified(change);
break;
case REMOVED:
onDocumentRemoved(change);
break;
}
}
onDataChanged();
}
public void startListening() {
if (mQuery != null && mRegistration == null) {
mRegistration = mQuery.addSnapshotListener(this);
}
}
public void stopListening() {
if (mRegistration != null) {
mRegistration.remove();
mRegistration = null;
}
mSnapshots.clear();
notifyDataSetChanged();
}
public void setQuery(Query query) {
// Stop listening
stopListening();
// Clear existing data
mSnapshots.clear();
notifyDataSetChanged();
// Listen to new query
mQuery = query;
startListening();
}
#Override
public int getItemCount() {
return mSnapshots.size();
}
protected DocumentSnapshot getSnapshot(int index) {
return mSnapshots.get(index);
}
protected void onDocumentAdded(DocumentChange change) {
mSnapshots.add(change.getNewIndex(), change.getDocument());
notifyItemInserted(change.getNewIndex());
}
protected void onDocumentModified(DocumentChange change) {
if (change.getOldIndex() == change.getNewIndex()) {
// Item changed but remained in same position
mSnapshots.set(change.getOldIndex(), change.getDocument());
notifyItemChanged(change.getOldIndex());
} else {
// Item changed and changed position
mSnapshots.remove(change.getOldIndex());
mSnapshots.add(change.getNewIndex(), change.getDocument());
notifyItemMoved(change.getOldIndex(), change.getNewIndex());
}
}
protected void onDocumentRemoved(DocumentChange change) {
mSnapshots.remove(change.getOldIndex());
notifyItemRemoved(change.getOldIndex());
}
protected void onError(FirebaseFirestoreException e) {};
protected void onDataChanged() {}
}
I used Firestore Adapter code which was given in samples of firestore documentation. Can anyone tell how to use the query object to load more data?
How to load the next 5 items in the recycler view when users scrolls to the end of the list?
You can paginate your Query's result using Query's methods like, startAt(), startAfter(), endAt(), endBefore() with a specified DocumentSnapshot.
If I considered your collection is called "interviews", you can add a method to your FireStoreAdapter like this:
private void paginate(final DocumentSnapshot last, final int limit) {
final Query subset;
if (last == null) {
subset = db.collection("interviews")
.limit(limit);
} else {
subset = db.collection("interviews")
.startAfter(last)
.limit(limit);
}
setQuery(subset);
}
You can perserve the last DocumentSnapshot within onEvent():
final List<DocumentChange> changes = documentSnapshots.getDocumentChanges();
final DocumentSnapshot lastDocument = changes.get(changes.size() - 1).getDocument();
Finally, when users scrolls to the end of the list:
paginate(lastDocument, 5);
And onDocumentAdded() will take care of it. Be carfure NOT to use startAt() because it will not execlude the last one (that already at the end of your list, and will duplicate it).

Pass data from firebase to object class

The issue I have is there're always Null Pointer Exception when I settext textview, so I cannot setText to my view.
I think the object didn't fill the field from getData method. How to fix this?
I am following this step https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection and this Parcelable object passing from android activity to fragment.
This is the error output from android studio console
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.plkbi, PID: 24337
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.my.plkbi.Layanan.getSyarat()' on a null object reference
at com.my.plkbi.SubMainFragment.onCreateView(SubMainFragment.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
EDIT: Add constructor to add object from other object, I follow this How do I copy an object in Java?
This is the object about the field database and Parcelable
public class Layanan implements Parcelable {
private String Nama;
private String Syarat;
private String Langkah;
private String Lampiran;
public Layanan(){
//this("connect to internet", "connect to internet", "connect to internet", "connect to internet");
}
//Constructor to add value from another object
public Layanan(Layanan another) {
this.nama = another.nama;
this.syarat = another.syarat;
this.langkah = another.langkah;
this.lampiran = another.lampiran;
this.deskripsi = another.deskripsi;
}
protected Layanan(Parcel in) {
Nama = in.readString();
Syarat = in.readString();
Langkah = in.readString();
Lampiran = in.readString();
}
public static final Creator<Layanan> CREATOR = new Creator<Layanan>() {
#Override
public Layanan createFromParcel(Parcel in) {
return new Layanan(in);
}
#Override
public Layanan[] newArray(int size) {
return new Layanan[size];
}
};
public static Layanan newInstance() {
Bundle args = new Bundle();
Layanan fragment = new Layanan();
fragment.setArguments(args);
return fragment;
}
private void setArguments(Bundle args) {
}
public String getNama() {
return Nama;
}
public String getSyarat() {
return Syarat;
}
public void setSyarat(String syarat) {
Syarat = syarat;
}
public String getLangkah() {
return Langkah;
}
public void setNama(String nama) {
Nama = nama;
}
public void setLangkah(String langkah) {
Langkah = langkah;
}
public String getLampiran() {
return Lampiran;
}
public void setLampiran(String lampiran) {
Lampiran = lampiran;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Nama);
dest.writeString(Syarat);
dest.writeString(Langkah);
dest.writeString(Lampiran);
}
}
This is how i get data from Firebase, it's inside in activity
Layanan UP;
Layanan GU;
Layanan LS;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
//initMF();
MainFragment homeFragment = MainFragment.newInstance();
Bundle extras = new Bundle();
getData("UP");
Log.d(TAG, "This is the value name of " + UP.getNama()); //Output: This is the value name of null
extras.putParcelable(UPParcelable, UP);
if (UP.getSyarat()!=null) Log.d(TAG, "Value Added");
if (UP.getSyarat()==null) Log.d(TAG, "Value not Added"); //Output: Value not Added
homeFragment.setArguments(extras);
getSupportFragmentManager().beginTransaction().add(R.id.main_activity, homeFragment).commit();
}
...
...
public void getData(final String p){
mFirebase.collection("panduan_layanan")
.whereEqualTo("nama", p)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent:error", e);
return;
}
Layanan newLayanan = new Layanan();
for (QueryDocumentSnapshot doc : value) {
if (doc.get("nama") != null && doc.get("syarat") != null && doc.get("langkah") != null && doc.get("lampiran")!= null){
newLayanan.setNama(doc.getString("nama"));
newLayanan.setLampiran(doc.getString("lampiran"));
newLayanan.setLangkah(doc.getString("langkah"));
newLayanan.setSyarat(doc.getString("syarat"));
Log.d(TAG, "Update data: Success" + p);
Log.d(TAG, "This is the " + p + " syarat" + newLayanan.getSyarat());
if (newLayanan.getSyarat() != null) Log.d(TAG, "new layanan is" + newLayanan.getNama()); //new layanan isUP, it is work too
}
}
if (p.equals("UP")) UP = new Layanan(newLayanan);
Log.d(TAG, "the" + UP.getNama()); //Output theUP so it is work in here
if (p.equals("GU")) GU = new Layanan(newLayanan);
if (p.equals("LS")) LS = new Layanan(newLayanan);
}
});
}
...
Thank you so much
You can't do that because firebase execute that block asynchronously. So the field doesn't get value immediately just like Frank's comment said

My app was working perfectly but now it keeps crashing

I'm using YouTube Data API v3 for searching YouTube videos on my app.
Last night was working perfectly but now it keeps crashing when I click search button. Can someone help me?
I've tried to regenerate API key but same error
when I change to: return mVideoList.size();
Error is: E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.youtubeexampleproject, PID: 7031
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at
YoutubeAdapter.getItemCount(YoutubeAdapter.java:108) the pointer goes to : return mVideolist.size();
and for code below error is:
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"location" : "fields",
"locationType" : "parameter",
"message" : "Invalid field selection activity",
"reason" : "invalidParameter"
} ],
"message" : "Invalid field selection activity"
}
'
query = youtube.search().list("id,snippet");
query.setKey(KEY);
query.setType("video");
query.setFields("items(id/kind,id/videoId,snippet/title,snippet/description,snippet/thumbnails/high/url/activity)");
} catch (IOException e) {
Log.d("YC", "Could not initialize: " + e);
}
}
public List<VideoItem> search(String keywords) {
query.setQ(keywords);
query.setMaxResults(MAXRESULTS);
try {
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
List<VideoItem> items = new ArrayList<VideoItem>();
if (results != null) {
items = setItemsList(results.iterator());
}
return items;
public class YoutubeAdapter extends RecyclerView.Adapter {
private Context mContext;
private List<VideoItem> mVideoList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public ImageView thumbnail;
public TextView video_title, video_id, video_description;
public RelativeLayout video_view;
public MyViewHolder(View view) {
super(view);
thumbnail = view.findViewById(R.id.video_thumbnail);
video_title = view.findViewById(R.id.video_title);
video_id = view.findViewById(R.id.video_id);
video_description = view.findViewById(R.id.video_description);
video_view = view.findViewById(R.id.video_view);
}
}
public YoutubeAdapter(Context mContext, List<VideoItem> mVideoList) {
this.mContext = mContext;
this.mVideoList = mVideoList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.video_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final VideoItem singleVideo = mVideoList.get(position);
holder.video_id.setText("Video ID : "+singleVideo.getId()+" ");
holder.video_title.setText(singleVideo.getTitle());
holder.video_description.setText(singleVideo.getDescription());
Picasso.get()
.load(singleVideo.getThumbnailURL()).resize(480,270)
.centerCrop()
.into(holder.thumbnail);
holder.video_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(mContext, PlayerActivity.class);
intent.putExtra("VIDEO_ID", singleVideo.getId());
intent.putExtra("VIDEO_TITLE",singleVideo.getTitle());
intent.putExtra("VIDEO_DESC",singleVideo.getDescription());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mVideoList == null ? 0 : mVideoList.size();
}
}'
Remove snippet/thumbnails/high/url/activity from fields and try
query.setFields("items(id/kind,id/videoId,snippet/title,snippet/description)");

NotSerializableException when FragmentActivity goes to background in Android

I have 5 fragments inside my activity where one fragment stays active at one time. Clicking on a recyclerview item opens another fragment and puts current fragment in the backstack.
The same code was working fine some days ago, but now the app is throwing NotSerializableException whenever I click the home button to put the app in background. I have tried putting the initializing the variables inside onStart and then giving the null value in onStop but that didn't work.
Fragment Code:
public class PaperListFragment extends Fragment implements Serializable {
private static final String TAG = "PaperListFragment";
private static final String QUESTIONS_FRAGMENT_TAG = "questions_fragment";
private static final String ADD_PAPER_FRAGMENT_TAG = "add_paper_fragment";
private OnFragmentActiveListener mOnFragmentActiveListener;
private TextView mHeadingText;
private Bundle mOutState;
private FirebaseAuth mAuth;
private DatabaseReference mDatabaseReference;
private ProgressBar mProgressBar;
private OnItemClickListener mOnItemClickListener;
private FloatingActionButton mFab;
private RecyclerView mRecyclerViewPaper;
private ArrayList<Paper> mPaperList = new ArrayList<>();
private Subject mSubject = new Subject();
private Exam mExam = new Exam();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recycler_list, container, false);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressbar_news);
mFab = (FloatingActionButton) rootView.findViewById(R.id.floatingActionButton);
mProgressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "onCreateView: Fragment created");
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
if (mAuth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
return null;
}
if (getArguments() != null) {
mOnFragmentActiveListener = (OnFragmentActiveListener) getArguments().getSerializable(Keys.FRAGMENT_ACTIVE_LISTENER);
mSubject = (Subject) getArguments().getSerializable(Keys.SUBJECT_KEY);
mExam = (Exam) getArguments().getSerializable(Keys.EXAMS_KEY);
}
mRecyclerViewPaper = (RecyclerView) rootView.findViewById(R.id.recycler_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()) {
#Override
public boolean canScrollVertically() {
return false;
}
};
mRecyclerViewPaper.setLayoutManager(layoutManager);
Log.d(TAG, "onCreateView: Layout Manager Set.");
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAddPaperFragment();
}
});
mOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView.ViewHolder holder, int position) {
Log.d(TAG, "onItemClicked: Clicked item position is: "+ position);
QuestionListFragment questionFragment = new QuestionListFragment();
questionFragment.setRetainInstance(true);
startFragment(position, questionFragment, QUESTIONS_FRAGMENT_TAG);
}
#Override
public void OnItemLongClicked(RecyclerView.ViewHolder holder, int position) {
}
};
mHeadingText = (TextView) rootView.findViewById(R.id.heading_textview);
mHeadingText.setText(mExam.getExam_name()+" > "+ mSubject.getSubject_name());
if (mOutState != null) {
mPaperList = (ArrayList<Paper>) mOutState.getSerializable(Keys.PAPER_LIST_KEY);
updateUI();
} else {
updateUIFromDatabase();
}
return rootView;
}
private void startFragment(int position, Fragment fragment, String fragmentTag) {
Paper paper = new Paper();
if (mPaperList.size() > 0) {
paper = mPaperList.get(position);
}
Bundle args = new Bundle();
args.putSerializable(Keys.EXAMS_KEY, mExam);
args.putSerializable(Keys.SUBJECT_KEY, mSubject);
args.putSerializable(Keys.PAPER, paper);
args.putSerializable(Keys.FRAGMENT_ACTIVE_LISTENER, mOnFragmentActiveListener);
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
fragmentTransaction.replace(R.id.questions_fragment_container, fragment, fragmentTag);
fragmentTransaction.addToBackStack(fragmentTag);
fragmentTransaction.commit();
}
private void startAddPaperFragment() {
AddPaperFragment addPaperFragment = new AddPaperFragment();
addPaperFragment.setRetainInstance(true);
startFragment(0, addPaperFragment, ADD_PAPER_FRAGMENT_TAG);
}
private void updateUIFromDatabase() {
if (getArguments() != null){
Exam exam = (Exam) getArguments().getSerializable(Keys.EXAMS_KEY);
Subject subject = (Subject) getArguments().getSerializable(Keys.SUBJECT_KEY);
DatabaseReference paperReference =
mDatabaseReference
.child(Keys.APP_DATA_KEY)
.child(Keys.EXAM_PAPERS)
.child(exam.getExam_name())
.child(subject.getSubject_name());
Query query = paperReference.orderByChild(Keys.TIME_ADDED);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mPaperList.clear();
for (DataSnapshot paperChild : dataSnapshot.getChildren()) {
mPaperList.add(paperChild.getValue(Paper.class));
}
updateUI();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void updateUI() {
PaperRecyclerAdapter adapter = new PaperRecyclerAdapter(
getActivity(),
mRecyclerViewPaper,
mPaperList,
mOnItemClickListener
);
mRecyclerViewPaper.setAdapter(adapter);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onResume() {
super.onResume();
if (getArguments()!=null){
mOnFragmentActiveListener.onFragmentActive(
this,
"Topics"
);
}
}
#Override
public void onPause() {
super.onPause();
mOutState = new Bundle();
mOutState.putSerializable(Keys.PAPER_LIST_KEY, mPaperList);
}
}
Exception:
2018-12-26 17:49:38.344 14834-14834/in.crazybytes.bankmaniaadmin E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.crazybytes.bankmaniaadmin, PID: 14834
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = in.crazybytes.bankmaniaadmin.activities.QuestionsActivity)
at android.os.Parcel.writeSerializable(Parcel.java:1526)
at android.os.Parcel.writeValue(Parcel.java:1474)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.support.v4.app.FragmentState.writeToParcel(FragmentState.java:124)
at android.os.Parcel.writeTypedArray(Parcel.java:1306)
at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:639)
at android.os.Parcel.writeParcelable(Parcel.java:1495)
at android.os.Parcel.writeValue(Parcel.java:1401)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3697)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.io.NotSerializableException: com.google.firebase.auth.internal.zzj
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1224)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at android.os.Parcel.writeSerializable(Parcel.java:1521)
at android.os.Parcel.writeValue(Parcel.java:1474) 
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723) 
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408) 
at android.os.Bundle.writeToParcel(Bundle.java:1133) 
at android.os.Parcel.writeBundle(Parcel.java:763) 
at android.support.v4.app.FragmentState.writeToParcel(FragmentState.java:124) 
at android.os.Parcel.writeTypedArray(Parcel.java:1306) 
at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:639) 
at android.os.Parcel.writeParcelable(Parcel.java:1495) 
at android.os.Parcel.writeValue(Parcel.java:1401) 
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723) 
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408) 
at android.os.Bundle.writeToParcel(Bundle.java:1133) 
at android.os.Parcel.writeBundle(Parcel.java:763) 
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3697) 
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Note: The weird thing is that one of fragment has the exact same code and is hosted inside the same activity, but when that fragment is active and app goes to background, interestingly the app is not crashing. 
**Exam Model Class:
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Exam implements Serializable {
private String mExam_name;
private String mExam_key;
private Long mTime_added;
private int mNum_subjects;
private int mNum_questions;
public Exam(String exam_name, String exam_key, Long time_added, int num_subjects, int num_questions) {
mExam_name = exam_name;
mExam_key = exam_key;
mTime_added = time_added;
mNum_subjects = num_subjects;
mNum_questions = num_questions;
}
public Exam() {
}
public String getExam_name() {
return mExam_name;
}
public void setExam_name(String exam_name) {
mExam_name = exam_name;
}
public String getExam_key() {
return mExam_key;
}
public void setExam_key(String exam_key) {
mExam_key = exam_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_subjects() {
return mNum_subjects;
}
public void setNum_subjects(int num_subjects) {
mNum_subjects = num_subjects;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
}
Paper Model Class
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Paper implements Serializable {
private String mPaper_name;
private String mPaper_key;
private Long mTime_added;
private int mNum_questions;
public Paper(String paper_name, String paper_key, Long time_added, int num_questions) {
mPaper_name = paper_name;
mPaper_key = paper_key;
mTime_added = time_added;
mNum_questions = num_questions;
}
public Paper() {
}
public String getPaper_key() {
return mPaper_key;
}
public void setPaper_key(String paper_key) {
mPaper_key = paper_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
public String getPaper_name() {
return mPaper_name;
}
public void setPaper_name(String paper_name) {
mPaper_name = paper_name;
}
}
Subject Model Class:
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Subject implements Serializable {
private String mSubject_name;
private String mSubject_key;
private Long mTime_added;
private int mNum_papers;
private int mNum_questions;
public Subject(String subject_name, String subject_key, Long time_added, int num_papers, int num_questions) {
mSubject_name = subject_name;
mSubject_key = subject_key;
mTime_added = time_added;
mNum_papers = num_papers;
mNum_questions = num_questions;
}
public Subject() {
}
public String getSubject_name() {
return mSubject_name;
}
public void setSubject_name(String subject_name) {
mSubject_name = subject_name;
}
public String getSubject_key() {
return mSubject_key;
}
public void setSubject_key(String subject_key) {
mSubject_key = subject_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_papers() {
return mNum_papers;
}
public void setNum_papers(int num_papers) {
mNum_papers = num_papers;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
}
Somehow QuestionsActivity is getting into the fragment save state, even if you don't intend for that to happen. While QuestionsActivity is being serialized, another object that is not serializable is being encountered. That's why you see TextViews and other things attempting to get serialized because all the instance variables of QuestionsActivity get serialized by default.
My best guess for why this is happening is due to this line:
args.putSerializable(Keys.FRAGMENT_ACTIVE_LISTENER, mOnFragmentActiveListener);
But it's difficult to know for sure without seeing where OnFragmentActiveListener is defined. I'm assuming either QuestionsActivity implements OnFragmentActiveListener, or QuestionsActivity defines OnFragmentActiveListener as an inner class. Either way, if you put an OnFragmentActiveListener into fragment arguments, you will encounter an exception because you indirectly are storing the entire QuestionsActivity as a fragment arg too. When a fragment stops, all fragment args become part of the fragment save state. And that's the cause of the error.
I would suggest not passing the OnFragmentActiveListener around as a fragment arg. If the OnFragmentActiveListener comes from the activity, just use getActivity() to get a reference to the activity and then get a reference to the listener.
I also noticed PaperListFragment implements Serializable and I'm assuming you did the same thing for QuestionsActivity. You probably did this to get around compile errors. But this has led to runtime errors because the instance variables on both of these classes are not all serializable. So to avoid more runtime issues, I would suggest never having activities or fragments implement serializable because these classes are inherently not serializable due to their members.

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!

Categories