RecyclerView works normally when used in activity but when used in fragment it gives error as below
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at restaurant.menu.fragments.MealsFragment.onCreate(MealsFragment.java:42)
fragment_meals.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".fragments.MealsFragment">
<!-- TODO: Update blank fragment layout -->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvMeals"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Items> ItemsList;
ItemsList= (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getActivity().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = getActivity().findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getActivity().getApplicationContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
}
As per the Fragment lifecycle guide, onCreate() is called before onCreateView. That means that your Fragment's view hasn't been created yet.
Instead, you want to move all of your code from onCreate() into onViewCreated() - that is the method that is called after onCreateView() and is where you can access your newly inflated views. Note that you cannot and should not be using getActivity().findViewById() - that finds views in your activity's layout, not in your fragment's layout:
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Related
i want to implement my_fragment1 into tab1 fragment how can i combine the fragment into fragment.
Tab1
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab1, container, false);
list_fragment fm = (list_fragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.My_Container_1_ID);
}
Tab1.xml
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button"
android:layout_toStartOf="#+id/button">
</FrameLayout>
If you want add another fragment to Tab1 fragment, you can use getChildFragmentManager() to add. In onActivityCreated of Tab1 fragment,
you can add another fragment
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getChildFragmentManager().beginTransaction()
.add(R.id.My_Container_1_ID, "your fragment here")
.commit();
}
And don't write codes after return .....
Im having trouble when creating an ArrayAdapter on my spinner. i don't know how to explain to you guys but people say a picture speaks 1000 words. so i provide a picture of my problem. please help me i really dont know what to do know.
this is my class
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return rootView;
}
}
this is my string.xml
<string-array name="select_font_size">
<item>Small</item>
<item>Default</item>
<item>Large</item>
<item>Larger</item>
</string-array>
and this is my xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal" />
I'd suggest to move the creation of the adapter inside the onActivityCreated callback when you know for sure that by calling getActivity() you will get a not null instance of the activity:
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = ArrayAdapter.createFromResource(getActivity(), R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
Try using the Application context, or context of the activity instantiating the fragment.
adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.select_font_size, android.R.layout.simple_spinner_item);
OR
adapter = ArrayAdapter.createFromResource(YOUR_ACTIVITY_CONTEXT_TO_BE_PASSED_INTO_FRAGMENT, R.array.select_font_size, android.R.layout.simple_spinner_item);
i am getting this errors.
Process: com.example.user.timey, PID: 17619
java.lang.RuntimeException: Your content must have a ListView whose id
attribute is 'android.R.id.list'
I have already defined android:id="#android:id/list" in my listview in xml.
This is my xml code:
<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="com.example.user.timey.OneFragment">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:divider="#E6E6E6"
android:dividerHeight="1dp" >
</ListView>
</RelativeLayout>
And this is my java code:
public class OneFragment extends ListFragment {
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
DBController controller = new DBController(getActivity());
ArrayList<HashMap<String, String>> scheduleList = controller.getAllSchedules();
if (scheduleList.size()!=0){
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(), scheduleList, R.layout.view_schedule_entry, new String[] { "scheduleId",
"scheduleName", "scheduleStartTime" }, new int[] {
R.id.scheduleId, R.id.scheduleName, R.id.scheduleTime });
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
Anyone knows whats wrong with my code? Thanks alot.
In your layout add id for ListView like this -
android:id="#+id/list"
Do not assign id to your views in layouts like #android:id/list.
Then in your onCreateView() method code get a reference to it -
ListView lv = (ListView) rootView.findViewById(R.id.list);
I'm trying to create gridview with images using Picasso library. I'm creating fragment with gridview and set adapter to gridview, but can not see anything on display.
Here is my adapter code:
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageUrls;
public GridViewAdapter(Context context, String[] imageUrls) {
super(context, R.layout.grid_item, imageUrls);
this.context = context;
this.imageUrls = imageUrls;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.grid_item, parent, false);
}
Picasso
.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into((ImageView) convertView);
return convertView;
}
}
Here is the code of my fragment
public class ViewMoviesFragment extends Fragment {
GridViewAdapter adapter;
public ViewMoviesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] eatFoodyImages = {
"http://i.imgur.com/rFLNqWI.jpg",
"http://i.imgur.com/C9pBVt7.jpg",
"http://i.imgur.com/rT5vXE1.jpg",
"http://i.imgur.com/aIy5R2k.jpg",
"http://i.imgur.com/MoJs9pT.jpg",
"http://i.imgur.com/S963yEM.jpg",
"http://i.imgur.com/rLR2cyc.jpg",
"http://i.imgur.com/SEPdUIx.jpg",
"http://i.imgur.com/aC9OjaM.jpg",
"http://i.imgur.com/76Jfv9b.jpg",
"http://i.imgur.com/fUX7EIB.jpg",
"http://i.imgur.com/syELajx.jpg",
"http://i.imgur.com/COzBnru.jpg",
"http://i.imgur.com/Z3QjilA.jpg",
};
View v= inflater.inflate(R.layout.grid_fragment, container, false);
GridView gridview = (GridView) v.findViewById(R.id.poster_view);
gridview.setAdapter(new GridViewAdapter(getActivity(), eatFoodyImages));
return v;
}
}
My activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new ViewMoviesFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
main_activity.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
grid_item.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
grid_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/poster_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2">
</GridView>
</FrameLayout>
When I run my app I get just white window. AndroidManifest.xml have internet permission access. Can anyone help me to show images in gridview?
The problem is in your GridViewAdapter
Picasso
.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into((ImageView) convertView);
convertView is a Framelayout
I get this error when I try to load my Fragment in my ActionBar.
Caused by: java.lang.IllegalArgumentException: No view found for id
0x7f070000 for fragment HomeFragment{4100e030 #0 id=0x7f070000}
public class HomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home, container, false);
}
}
The below is my mainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime_mobile_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab homeTab = actionBar.newTab();
homeTab.setText("Home");
homeTab.setIcon(R.drawable.home);
Fragment homeFragment = new HomeFragment();
homeTab.setTabListener(new MyTabsListener(homeFragment));
actionBar.addTab(homeTab);
}
MainActivity XML
<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" >
</RelativeLayout>
you should input viewGroup resource ID which is ContentView in ParentActivity.
does you Parent Activity have LinearLayout or Relativelayout as ContentView.
if yes, you should choose it in inflate method's augument.