Have implemented a recycler view found on my notification fragments on adding itesm on the same fragments no problem occurs but when i try to add items from another fragment it throws and eror JavaNullPointException.
here is my fragment that has the recycler view
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);
notimodels = new ArrayList<> ();
mRecyclerView = v.findViewById(R.id.notificationsRecycler);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
// get data from the notificiation
return v;
}
#Override
public void onStart() {
super.onStart ();
swipeRefreshLayout.setRefreshing(true);
fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
}
public void fillNotification(int mImage, String mtext, String mtext2, String mDate)
{
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager (getContext ());
mAdapter = new NotificationAdapter (notimodels);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
notimodels.add (0,new NotificationModel (mImage,mtext,mtext2,mDate));
}
}
**When i try to call the function from other fragments like tis forexample""
NotificationFragmentCict notificationFragmentCict =new NotificationFragmentCict ();
notificationFragmentCict.fillNotification (R.drawable.bursar, "Bursar", "your clreard","min");
My App crushes and throws this error
Process: com.univibezstudios.ocappservice.ocapp, PID: 3380
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
The problem is this one This error is showing because your fragment's view is not created yet. That's why recyclerview is null and you're invoking setHasFixedSize(...) method on you null recyclerview. but icant solve it any help guys
You need to initialize the recycler view which you left out of the function fillNotification:
mRecyclerView = v.findViewById(R.id.notificationsRecycler);
you also need the ArrayList in the second fragment:
notimodels = new ArrayList<> ();
Related
I have only the mainActivity and I use 3 fragnments and navigate through them with a bottomnav. All good until now, Im able to run the app on the emulator but when I select this fragment with my RecyclerView I get this error message and the app crashes
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
I've seen a lot of alike answers and try to make my way arround but no success, so Im thinking Im not putting the code in the correct way or in the correct places, can you give me some advice?
Here is the Fragment code
public class administrador_atletas extends Fragment {
//Lista de atletas
public List<lista_atletas> lista_atl;
public RecyclerView rcc_lista_atletas;
public lista_atletas_adaptador adaptador_lista_atletas;
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_administrador_atletas, container, false);
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);
return view;
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linear = new LinearLayoutManager(this.getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);
rcc_lista_atletas.setLayoutManager(linear);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// do your variables initialisations here except Views!!!
data();
iniciar_adaptador_atletas();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
public void data(){
lista_atl = new ArrayList<>();
lista_atl.add(new lista_atletas("Astrid Ruvalcaba Ramos", "Esgrima"));
lista_atl.add(new lista_atletas("Daniel Sanchez Cuevas", "G. Artistica"));
lista_atl.add(new lista_atletas("Alexa Luna Contreras", "TKD"));
lista_atl.add(new lista_atletas("Paul Carillo Mendez", "Natacion"));
lista_atl.add(new lista_atletas("Karen Mendoza Galindo", "Boxeo"));
lista_atl.add(new lista_atletas("Marco Torres Miranda", "Tiro con arco"));
}
public void iniciar_adaptador_atletas(){
adaptador_lista_atletas = new lista_atletas_adaptador(lista_atl);
rcc_lista_atletas.setAdapter(adaptador_lista_atletas);
}
Thanks in advance
EDIT: I just moved
data();
iniciar_adaptador_atletas();
Bellow
rcc_lista_atletas.setLayoutManager(linear);
In onCreateView so I have this
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_administrador_atletas, container, false);
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);
LinearLayoutManager linear = new LinearLayoutManager(this.getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);
rcc_lista_atletas.setLayoutManager(linear);
data();
iniciar_adaptador_atletas();
return view;
}
And it worked, now Im able to enter the fragment with my data
Many thanks to all, your info was very useful!
As the error message says, you are calling the method setAdapter on a null-valued variable (probably rcc_lista_atletas).
While the error is not exactly in the source code you published (you should update your post with the full code), I suppose one of the methods, data() or iniciar_adaptador_atletas(), is calling 'setAdapter'.
You must remember that onCreate is executed before onCreateView. So, you're probably calling setAdapter before the onCreateView is executed and, doing so, rcc_lista_atletas is still null. Move data() and iniciar_adaptador_atletas() to the line before "return view;" in onCreateView and test it again.
This is the best we can do without checking you full code.
It seems, you try to connect adapter to recyclerView before created recyclerView. So, try to move iniciar_adaptador_atletas(); to the bottom of
rcc_lista_atletas = (RecyclerView)view.findViewById(R.id.recycler_administrador_atletas);
I have 3 different activities. 1 extends Application and realm is configured in this activity. 2. Data is added to Realm from 2nd activity . 3. Data is to be displayed in the 3rd activity. I am unable to do the 3rd part. I am unable to get an instance of Realm in the 3rd activity. The following is Application(1st activity that I mentioned)
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(realmConfiguration);
}
the following is the code for adding data to realm which is in a fragment inside 2nd activity(PurchaseDetailsActivity).
private void addDataToRealm(DBPurchase model) {
mRealm.beginTransaction();
DBPurchase dbPurchaseModel = new DBPurchase();
dbPurchaseModel.setId(id);
dbPurchaseModel.setAmountPayed(model.getAmountPayed());
dbPurchaseModel.setCredit(model.getCredit());
mRealm.insertOrUpdate(dbPurchaseModel);
mRealm.commitTransaction();
id++;
the last one is the fragment which is inside 3rd Activity.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_purchase_items, container, false);
purchaseTotalListAdapter = new PurchaseTotalListAdapter(getContext(), mDBPurchaseArrayList, PurchasesTotalListFragment.this);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(purchaseTotalListAdapter);
Realm.getDefaultInstance();
return view;
}
I have of null object inside a fragment. The basic idea is that I have an activity that fetches a database asynchronously. However my recyclerview where I will populate the data lives into a fragment. The pseudo-code is more or less
ACTIVITY:
public void onCreate(Bundle savedInstanceState) {
//kicks off a query to the server
mData = new Gson().fromJson(getIntent().getExtras().getString(Constants.MYDATA), MyData.class);
if (mVenue == null) {
finish();
return;
}
// a bunch of stuff
// create a fragment
mMyFrag = new MyFrag();
}
public void CallBackWhenDone(final List<DataSet> dataset) {
// notify the frag that we are done
mMyFrag.notifyDataSetChanged(messages);
}
FRAGMENT:
private RecyclerView mRV;
private ParentActivity mActivity;
private ActivityAsynchData mAsynchData;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler, container, false);
mRV = (RecyclerView) view.findViewById(R.id.list);
mRV.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext(), LinearLayoutManager.VERTICAL, false));
if (null != mActivity) {
mAsynchData = mActivity.GetAsynchData();
}
if (null != mAsynchData) {
mRV.setAdapter(new MyRecyclerAdapter(getActivity(), mAsynchData));
}
}
// mRV is null when the activity "CallBackWhenDone" calls the frag
// all private variables are gone! why?
public void notifyDataSetChanged(final List<Message> messages) {
MyRecyclerAdapter adapter = ((MyRecyclerAdapter) mRV.getAdapter());
adapter.setMessageList(messages);
adapter.notifyDataSetChanged();
}
I ended up hacking my recycler (mRV in this case) view to be static, but this looks super hacked.
any way around? In other words how can I fetch my "mRV" after the fragment has been created and the private vars are all gone.
What i could understand is, that you initialised the fragment and try to access the recycler view in that but its throwing you null. I am not surprised to see it being as null. The way you have called the method is not correct.You need to get the hosted and already running fragment, instance try doing this:
if you are using support fragment use getSupportFragmentManager instead of getFragmentManager.
MyFrag fragment = (MyFrag) getFragmentManager().findFragmentById(R.id.fragmentHolder);
fragment.<specific_function_name>();
Here , the R.id.fragmentHolder is the id of the frame layout or any layout that you are using to host your fragment inside the an activity.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
I was using a recyclerview in an activity and now decided to use it in a fragment instead. Now my code crashes at layoutmanager = new LinearLayoutManager (globalContext); with a NullPointerException.
I have no idea why. As I said it worked perfectly fine when used in activity.
I'm using Xamarin but that really doesn't make any difference.
I have only included the first parts of the code as app crashes before reaching others.
private Context globalContext = null;
RecyclerView recyclerview;
RecyclerView.LayoutManager layoutmanager;
NewsAdapter adapter;
public LatestNewsFragment()
{
this.RetainInstance = true;
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);
// Get our RecyclerView layout:
recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);
return view;
}
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
globalContext = this.Context;
//............................................................
// Layout Manager Setup:
// Use the built-in linear layout manager:
layoutmanager = new LinearLayoutManager (globalContext);
// Plug the layout manager into the RecyclerView:
recyclerview.SetLayoutManager (layoutmanager);
//............................................................
// Adapter Setup:
// Create an adapter for the RecyclerView, and pass it the
// data set to manage:
var rest = new RestAccess();
var listofarticles = await rest.ListArticlesAsync("somesource", "1");
adapter = new NewsAdapter (listofarticles, globalContext);
// Register the item click handler (below) with the adapter:
adapter.ItemClick += OnItemClick;
// Plug the adapter into the RecyclerView:
recyclerview.SetAdapter (adapter);
}
// Handler for the item click event:
void OnItemClick (object sender, int position)
{
// Display a toast that briefly shows the enumeration of the selected photo:
int photoNum = position + 1;
Toast.MakeText(globalContext, "This is card number " + photoNum, ToastLength.Short).Show();
}
}
Edit:
So I changed the OnCreateView to :
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);
// Get our RecyclerView layout:
recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);
// Plug the layout manager into the RecyclerView:
recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));
return view;
}
And still getting nullpointer exception at recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));
Edit 2:
variable recyclerview is actually null. Don't know why.
Answer:
My app was crashing for two reasons:
1- layoutmanager must be defined in OnCreateView but I was doing it in OnActivityCreated.
2- My fragment layout file didn't include the RecyclerView.
You need to set LayoutManager in onCreateView() after initializing RecyclerView, instead of setting in onActivityCreated():
mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(newLinearLayoutManager(mRecyclerView.getContext()));
Instead of this.Context use getActivity() to get Context in Fragment class. Change:
globalContext = this.Context;
to
globalContext = getActivity();
Try with getActivity()
layoutmanager = new LinearLayoutManager (getActivity());
Im using 3 fragments in my ViewPager adapter. I will be loading data from Parse(parse.com) and displaying them in recycler views. The following code is causing my app to crash. What my understanding is that when my MainActivity loads, this is my first fragment ie, it gets viewed by user immediately so the setUserVisibleHint function gets called immediately and in that v.findViewById code causes a null pointer exception since setContentView hasnt/ may not been called. My proof for this is if i add a 1sec delay to setUserVisisbleHint then my code works properly.
Now I want to add server PULL requests using Parse, add data in a list to an adapter and populate recyclerview AFTER user views the page so
1) Should i add all the code in setUserVisisbleHint and just add a 0.5secc delay so it gets executed after setContentView is called ensuring I dont get a null pointer exception error OR
2) Is there a better way/ other functions I can use to achieve the same?
public class NewsFeed extends Fragment {
LinearLayoutManager mLayoutManager;
boolean _areLecturesLoaded=false;
View v;
ProgressBar bar;
public NewsFeed() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
v=inflater.inflate(R.layout.fragment_news_feed, container, false);
RecyclerView mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(v.getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
MyStickyAdapter mAdapter = new MyStickyAdapter(v.getContext());
mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(mAdapter));
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !_areLecturesLoaded ) {
_areLecturesLoaded = true;
v.findViewById(R.id.asd).setVisibility(View.GONE);
}
}
}//Closes Fragment
Im using this library for my recycler view StickyHeaderRecyclerView
I would highly recommend avoiding adding delays especially if you're running this on the main thread. To avoid the NPE, try moving the findViewById(R.id.asd) into your onCreateView method after you inflate the view:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
v=inflater.inflate(R.layout.fragment_news_feed, container, false);
v.findViewById(R.id.asd).setVisibility(View.GONE);
This is assuming that R.id.asd is in R.layout.fragment_news_feed
This post could also provide some insight:
setUserVisibleHint called before onCreateView in Fragment