ive a metod which check that internet connection work or no. Also ive two metods - if internet works get data from api and load in recyclerview and it's work correctly, but when im copy the same metod to the "offline mode" and change, that the data will load from Realm Database im getting error like this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
At the point i dont know why im getting it, below some code which generate my problem:
else if(isOnline() == false){
try {
RealmResults<ResultModel> obj = realm.where(ResultModel.class).findAll();
for(int i=1; i < obj.size(); i ){
newList.add(new ResultModelClass(
String.valueOf(obj.get(i).getId()),
obj.get(i).getName(),
obj.get(i).getSurname());
}
n1RecyclerView = getActivity().findViewById(R.id.recyclerN1View);
n1RecyclerView.setHasFixedSize(true);
n1ListAdapter adapter = new ResultAdapter(newList);
n1RecyclerViewLM = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
n1RecyclerView.setLayoutManager(n1RecyclerViewLM);
n1RecyclerView.setItemAnimator(new DefaultItemAnimator());
n1RecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Log.d("_API_TEST", "Offline mode");
} catch (Exception e){
Log.d("_OFFLINE_MODE", "setCatsInfo has problem: " e);
}
}
Everything looks good for me, exactly the same example but after try im getting question if response.code == 200 then download and parse data using this same newList.add mode, and it's work. Im very confused... Im also trying with making two recyclerviews names like "n1RecyclerView" and "n1RecyclerView2" but it's for nothing.
CodePudding user response:
RecyclerView reference null there. getActivity() it's a generic activity reference. So, you've to cast your activity.
((YOUR_ACTIVITY) getActivity()).findViewById(R.id.recyclerN1View);
CodePudding user response:
Ok i got it. There is a problem with that, this view will load too fast. The simplest answer is to use delay like:
import android.os.Handler;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
RealmResults<ResultModel> obj = realm.where(ResultModel.class).findAll();
for(int i=1; i < obj.size(); i ){
newList.add(new ResultModelClass(
String.valueOf(obj.get(i).getId()),
obj.get(i).getName(),
obj.get(i).getSurname());
}
n1RecyclerView = getActivity().findViewById(R.id.recyclerN1View);
n1RecyclerView.setHasFixedSize(true);
n1ListAdapter adapter = new ResultAdapter(newList);
n1RecyclerViewLM = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
n1RecyclerView.setLayoutManager(n1RecyclerViewLM);
n1RecyclerView.setItemAnimator(new DefaultItemAnimator());
n1RecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Log.d("_API_TEST", "Offline mode");
}
}, 500);