Error on the second fragment with recycler view layout manager - android

I have a mainActivity with a fragment container which i set one of three fragments in it.
In each one i have a recycler view and I move to the next fragment on an item click.
The first fragment with the recyclerView is set as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_courses, container, false);
mRootRef = FirebaseDatabase.getInstance().getReference();
mCoursesList = view.findViewById(R.id.courses_rv);
linearLayoutManager = new LinearLayoutManager(getContext());
mCoursesList.setLayoutManager(linearLayoutManager);
mCoursesList.setHasFixedSize(true);
updateView();
return view;
}
the error happens when entering the second fragment which is done as
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
mSubjectsList = view.findViewById(R.id.subjects_rv);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}
// Inflate the layout for this fragment
return view;
}
Apparently they are the same but with the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
The XML files
Main2Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.crash.mathtest.Views.Main2Activity">
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
></LinearLayout>
</LinearLayout>
CoureseFragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.crash.mathtest.Views.CoursesFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/courses_rv"
/>
</FrameLayout>
Subjects fragment is the same as courses fragment
Again, this only appears on the second fragment (onCreateView)
The error points to the setLayoutManager(linearLayout)
Can't I make new layouts in the same activity ?
doesn't the new one override the last ?

You don't need to declare twice setLayoutManager() method. You are doing:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setLayoutManager(mSubjectsList.getLayoutManager());
Instead of this, just declare:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
Try to move your recyclerView data from onCreateView to onViewCreated.
Inside onCreateView() method:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_fragment, container, false);
}
Now add your recyclerView content to onViewCreated() method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerViewId);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
}

UPDATE
do this stuff in
onActivityCreated from onCreateView
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}

Related

recycler view null point exception in fragment

I have a recyclerview in fragment. When I run the app i get the following message.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
I have searched and found people with similar problems, but it hasn't helped me. The recyclerview is null in the fragment. Here is my code:
I call the fragment from the main activity here on the onCreate:
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
trans.commit();
trans.show(recyclerViewFragment);
Here is my recyclerfragment:
public class RecyclerViewFragment extends Fragment
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
static SQLiteDatabase db;
ArrayList<MyMarker> markerArrayList;
private MyAdapter adapter;
private String TAG = "recyclerview fragment";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(markerArrayList, this);
recyclerView.setAdapter(adapter);
return view;
Here is my xml for the recyclerview Fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecyclerView.RecyclerViewFragment"
android:background="#a6ffffff">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_in_fragment"
android:scrollbars="vertical"
android:layout_below="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Thanks very much if you can help.
You should use onViewCreated() to access the views
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(markerArrayList, this);
recyclerView.setAdapter(adapter);
}

Vertical LinearLayoutManager Crashes App

So I am using two RecyclerViews in a fragment in my android app. One of them scrolls horizontally and the other scrolls vertically. Yet for some strange reason the vertical one always crashes with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' on a null object reference
Here's how I set up the RecyclerViews:
#InjectView(R.id.nearby_recycler)
RecyclerView nearbyRecycler;
RecyclerView.LayoutManager nearbyLayoutManager;
#InjectView(R.id.buddies_recycler)
RecyclerView buddiesRecycler;
RecyclerView.LayoutManager buddiesLayoutManager;
public static HomeFragment newInstance(){
return new HomeFragment();
}
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.inject(this, root);
nearbyLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
nearbyRecycler.setLayoutManager(nearbyLayoutManager);
nearbyRecycler.setAdapter(buddiesAdapter);
buddiesLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
buddiesRecycler.setLayoutManager(buddiesLayoutManager);
buddiesRecycler.setAdapter(buddiesAdapter);
return root;
}
The RecyclerViews in fragment_home.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/nearby_recycler"
android:layout_width="match_parent"
android:layout_height="#dimen/icon_large"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/buddies_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
As soon as I switch the orientation to Horizontal, the RecyclerView crashes as soon as I scroll it. Any suggestions?
I figured it out! So I'm completely unsure about why this was an issue, but the root of the problem was that my fragment was inside a view pager. I took it out of the view pager for now and added the fragment through fragment transaction.
My previous method of adding the fragment was this way.
MainActivity.java
HomeFragment homeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
homeFragment = HomeFragment.newInstance();
mFragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return homeFragment;
}
#Override
public int getCount() {
return 1;
}
};
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context=".ui.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_below="#id/toolbar1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
I changed it to this:
MainActivity.java
HomeFragment homeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, homeFragment)
.commit();
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context=".ui.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

List View in a fragment is not working?

I am using the following code for using a listview in a fragment. I don't know why it is not working?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
return view;
}
I tried the follwing solving, but it didn't work either: List View in Fragment not working
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
// listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
//
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
//
// listView.setAdapter(adapter);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
}
Please help me.
Edit 1:fragment_home.xml is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.shiza.callhistorycontrol.Home">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/theListOfHistoryControl" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/theListOfHistoryControl">
</ListView>
</LinearLayout>

android.widget.RelativeLayout cannot be cast to android.support.v7.widget.RecyclerView

I have a problem in my NavigationDrawer layout with error:
android.widget.RelativeLayout cannot be cast to android.support.v7.widget.RecyclerView
This is my onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_drawer, container, false);
mRecyclerView.setClipToPadding(false);
mAdapter = new NavigationDrawerAdapter(getActivity(), new NavigationDrawerAdapter.ClickListener() {
#Override
public void onClick(int index) {
selectItem(index);
}
#Override
public boolean onLongClick(final int index) {
Pins.Item item = mAdapter.getItem(index);
Utils.showConfirmDialog(getActivity(), R.string.remove_shortcut,
R.string.confirm_remove_shortcut, item.getDisplay(getActivity()), new CustomDialog.SimpleClickListener() {
#Override
public void onPositive(int which, View view) {
Pins.remove(getActivity(), index);
mAdapter.reload(getActivity());
}
}
);
return false;
}
});
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter.setCheckedPos(mCurrentSelectedPosition);
return mRecyclerView;
}
And this is the fragment_drawer layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/cover_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/banner" />
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cover_bg"
android:background="?drawer_background"
android:scrollbars="vertical" />
</RelativeLayout>
I don't know how it can't cast the RelativeLayout.. Same crash with LinearLayout.
mRecyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_drawer, container, false);
Your fragment_drawer layout does not have a RecyclerView as its root element. It has a RelativeLayout as its root element. Hence, inflate() will be returning the RelativeLayout, which itself has the RecyclerView inside of it.
Change your code to:
View drawer = inflater.inflate(R.layout.fragment_drawer, container, false);
mRecyclerView = (RecyclerView) drawer.findViewById(android.R.id.list);
Here, we get the RecyclerView by finding the #android:id/list widget inside the inflated layout.

Passing data from ListView to Fragment

I have a ListView in my fist screen that shows some information. When I click on each item, I have another listView with new information and textview in the same page, I want to show the pervious list view row in text view,
would you please let me know how can I implement this,
Thanks in advance!
here is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="######">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone"
android:text="test" />
<TextView
android:id="#+id/list_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:text="#string/no_message"
android:textColor="#000000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:gravity="center"></TextView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
Here is my java file that shows the listview and
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView)view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getActivity().getActionBar().setTitle(R.string.title_forms);
TextView details = (TextView)view.findViewById(R.id.detail_header);
details.setVisibility(View.VISIBLE);
return view;
}
Here is one of my fragment that has onItemClick Listener
public class ListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final String TAG = "ListFragment";
private ListView listView;
private ArrayList<String> testIds;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
tripIds = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);
return view;
}
Here is my onItemClick :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
chooseTest(testIds.get(position));
String selectedTestId = testIds.get(position);
Helpers.saveToSharedPreferences(getActivity(),
Constants_Prefs.SELECTED_TOP_LEVEL_RECORD,
Constants_Keys.SELECTED_TEST_ID,
selectedTestId);
I don't know how can I get that information
FormTypeListFragment passDataTo = new FormTypeListFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA", selectedTestId);
passDataTo.setArguments(bundle);
}
Before launching your fragment to display selected item use setArguments() method to add key value pair of string in your case, Then in your fragment on createView use fragments method getArguments() to retain your passed string
Pass the value in bundle as :
Set :
YourFragment fragmnt = new YourFragment ();
Bundle bundle = new Bundle();
bundle.putString("item","name");
fragmnt.setArgument(bundle);
Get :
Then in your Fragment, retrieve the data (e.g. in onCreate()) with:
Bundle bundle = this.getArguments();
String myValue = bundle.getInt("item", "");

Categories

Resources