ListView 'android.R.id.list' is not found in ListFragment - java

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);

Related

TextView in Fragment Returning Null in Android Studio

i am new to Android Studio.. i am facing null pointer exception error on my TextView inside a Fragment, please help..here is my code. this is nothing but a simple interface between two fragments. i am getting Null pointer exception error when i click on an item in ListView Fragment. for sure the TextView in DetailsFragment didn't assign or point to the source of whatever it is. please help on solving this.
public class MainActivity extends AppCompatActivity implements list_Fragment.ItemSelected {
ArrayList<String> Descriptions = new ArrayList<String>();;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Descriptions.add("Description for Item 1");
Descriptions.add("Description for Item 2");
Descriptions.add("Description for Item 3");
Descriptions.add("Description for Item 4");
tvDescription = findViewById(R.id.tvDescription);
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(Descriptions.get(index));
}}
list_fragment
public class list_Fragment extends ListFragment {
ArrayList<String> Data = new ArrayList<String>();
ItemSelected activity;
public interface ItemSelected{
void onItemSelected(int index);
}
public list_Fragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity=(ItemSelected) context;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Data.add("Item 1");
Data.add("Item 2");
Data.add("Item 3");
Data.add("Item 4");
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Data));
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
activity.onItemSelected(position);
}
}
and the details Fragment code, where i am getting the error i believe, is
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return (LinearLayout) inflater.inflate(R.layout.fragment_details, container, false);
}
}
Main XML file
<?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:id="#+id/ll_Horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/listfragmentView"
android:name="com.example.fragmentcheck.list_Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="#android:color/holo_blue_dark"
tools:layout="#layout/fragment_list_" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/detailsfragmentView"
android:name="com.example.fragmentcheck.DetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/purple_200"
tools:layout="#layout/fragment_details" />
</LinearLayout>
ListFragment XML
<?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:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_primary_variant"
android:orientation="vertical"
tools:context=".list_Fragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
DetailsFragment XML
<?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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_on_secondary"
android:orientation="vertical"
tools:context=".DetailsFragment">
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</LinearLayout>
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fragmentcheck, PID: 28112
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object r*emphasized text*eference
at com.example.fragmentcheck.MainActivity.onItemSelected(MainActivity.java:34)
at com.example.fragmentcheck.list_Fragment.onListItemClick(list_Fragment.java:54)
tvDescription is in the DetailsFragment layout, you need to do any layout configuration in the code for that Class
i.e.
class DetailsFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
You have tvDescription in DetailsFragment xml, while you are finding it's id in MainAcitvity. MainActivity just have FragmentContainerView , it doen't have any text view inside it.
You need to inflate the Fragment's view and call findViewById() on the View it returns.
Updated DetailsFragment
public class DetailsFragment extends Fragment {
TextView tvDescription;
public DetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
Change both: androidx.fragment.app.FragmentContainerView
To: fragment
In the main_activity xml

RecyclerView crashes with NullPointerException in Fragment

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);
}
}

Custom Adapter is not showing anything from a Fragment [duplicate]

This question already has answers here:
ListView not showing at all
(1 answer)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
I have a custom Adapter called MyAdapter where i'm trying to load a layout which supposedly should be inserted into a listview, but even when Android is not giving errors the view is showing in blank.
In the next screenshot, i show what i get after build my app.
What i'm expecting to load is my layout into my listview:
ListView
<?xml version="1.0" encoding="utf-8"?>
<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=".Fragments.NewsFragment">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
Layout
<?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:id="#+id/list_item"
android:layout_height="80dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageabdcf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_margin="25dp"
tools:srcCompat="#android:drawable/btn_star_big_on" />
<TextView
android:id="#+id/textabcdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
NewsFragment.java
public class NewsFragment extends Fragment {
private ListView listView;
private List<String> names;
public NewsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) v.findViewById(R.id.listView);
names = new ArrayList<String>();
names.add("Fernando");
names.add("Roberto");
names.add("Torres");
names.add("Urban");
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, names);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getView().getContext(), "Clicked: " + names.get(position), Toast.LENGTH_LONG).show();
}
});
MyAdapter myAdapter = new MyAdapter(v.getContext(), R.layout.card_view_news, names);
listView.setAdapter(myAdapter);
// Inflate the layout for this fragment
return v;
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<String> names;
public MyAdapter(Context context, int layout, List<String> names) {
this.context = context;
this.layout = layout;
this.names = names;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return this.names.get(position);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View v = convertView;
LayoutInflater layoutInflater = LayoutInflater.from(this.context);
v = layoutInflater.inflate(R.layout.fragment_news, null);
String currentName = names.get(position);
//currentName = (String) getItem(position);
TextView textView = (TextView) v.findViewById(R.id.textabcdf);
textView.setText(currentName);
return v;
}
}
And what i'm expecting for is something like:

android.support.v4.widget.NestedScrollView cannot be cast to android.support.v7.widget.RecyclerView

Good afternoon,
I am trying to create a fragment with a RecyclerView including items.
Above those items, I need to put a header with some filters.
Here is the fragment's xml (fragment_products_list) :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="12sp"
android:id="#+id/filters_frame">
<include layout="#layout/expandable_filters"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Here is the OnCreateView in my Fragment java file (ListFragment.java) :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView rv = (RecyclerView) inflater.inflate(
R.layout.fragment_products_list, container, false);
//Product filters
expandFiltersButton = (ImageButton) getView().findViewById(R.id.expand_filters);
expandableZone = (LinearLayout) getView().findViewById(R.id.expandable_zone);
expandFiltersButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(expandableZone.isShown()){
expandableZone.setVisibility(View.GONE);
expandFiltersButton.setImageResource(R.drawable.ic_more_24dp);
}else{
expandableZone.setVisibility(View.VISIBLE);
expandFiltersButton.setImageResource(R.drawable.ic_less_24dp);
}
}
});
setupRecyclerView(rv);
mRecyclerView = rv;
loadUpdates();
return rv;
}
I have this error code when I am trying to run the app :
android.support.v4.widget.NestedScrollView cannot be cast to android.support.v7.widget.RecyclerView
What is the problem and how can I solve it?
Thanks for your help!
Try this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_products_list, container, false);
//Product filters
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
expandFiltersButton = (ImageButton) view.findViewById(R.id.expand_filters);
expandableZone = (LinearLayout) view.findViewById(R.id.expandable_zone);
expandFiltersButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(expandableZone.isShown()){
expandableZone.setVisibility(View.GONE);
expandFiltersButton.setImageResource(R.drawable.ic_more_24dp);
}else{
expandableZone.setVisibility(View.VISIBLE);
expandFiltersButton.setImageResource(R.drawable.ic_less_24dp);
}
}
});
setupRecyclerView(rv);
mRecyclerView = rv;
loadUpdates();
return view;
}

Implement SwipeRefresh Layout

I am trying to implement the Pull to refresh feature in Android.
For this, I ended up using SwipeRefresLayout from Support library.
But it is not working as I wanted to.
I am needed to implement it inside fragment.
here is the code for fragment_home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/group_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="45dp" />
</android.support.v4.widget.SwipeRefreshLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id" >
</com.google.android.gms.ads.AdView>
</FrameLayout>
</LinearLayout>
And this is the fragment placed inside the MainActivity.java
public static class HomeFragment extends Fragment {
public static final String ARG_CATEGORY_NUMBER = "category_number";
private UiLifecycleHelper uiHelper;
public int currentimageindex = 0;
private SwipeRefreshLayout swipeLayout;
public HomeFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
//SWIPE TO REFRESH
swipeLayout = (SwipeRefreshLayout) container.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener((OnRefreshListener) getActivity());
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
ListView hlvCategory = (ListView) rootView
.findViewById(R.id.group_content);
AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
HomeJsonData hjd = new HomeJsonData(getActivity(), hlvCategory,
mAdView, mDrawerList);
hjd.execute();
return rootView;
}
//SWIPE TO REFRESH
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
}
But this gives out the error as like it was unable to find the class for SwipeRefresh Layout.
Can you suggest me how can i implement it here??
Here in your fragment i found the problem is with set up the refresh listener
public static class HomeFragment extends Fragment implements OnRefreshListener{
public static final String ARG_CATEGORY_NUMBER = "category_number";
private UiLifecycleHelper uiHelper;
public int currentimageindex = 0;
private SwipeRefreshLayout swipeLayout;
public HomeFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
//SWIPE TO REFRESH
swipeLayout = (SwipeRefreshLayout) container.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
ListView hlvCategory = (ListView) rootView
.findViewById(R.id.group_content);
AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
HomeJsonData hjd = new HomeJsonData(getActivity(), hlvCategory,
mAdView, mDrawerList);
hjd.execute();
return rootView;
}
//SWIPE TO REFRESH
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
}
and make sure you have added supportV4 library
try as above this will help you,happy coding :)
Please refer this links, this may help
https://developer.android.com/samples/SwipeRefreshLayoutBasic/src/com.example.android.swiperefreshlayoutbasic/SwipeRefreshLayoutBasicFragment.html
http://antonioleiva.com/swiperefreshlayout/
You should implement the OnRefreshListener in your Fargment
public static class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener
and set swipeLayout.setOnRefreshListener(this);

Categories