Bjorn Fontaine
Bjorn Fontaine

Reputation: 464

NullReferenceException when using Fragment in ListView android

I have an app where I show a listview in a fragment. however, on creating the listview I'm getting a null ref exception. I'm not sure why because on other fragments it is working just fine. this is my fragment and my layout page.

fragment :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using CardAppReal.Assets;
using CardAppReal.Lib.Models;
using SQLite;
using Environment = System.Environment;
using Fragment = Android.Support.V4.App.Fragment;

namespace NavigationDrawerTest.Fragments
{
    public class WishlistFragment : Fragment
    {
        private List<Card> _cards;

        public WishlistFragment()
        {
            this.RetainInstance = true;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.WishlistPage, null);
            LoadWishlist();
            return view;
        }

        private void ListViewCards_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Android.Support.V4.App.Fragment fragment = null;
            var listView = sender as ListView;
            var t = _cards[e.Position];
            Android.Widget.Toast.MakeText(this.Activity, t.name, Android.Widget.ToastLength.Short).Show();
            Bundle bundle = new Bundle();
            bundle.PutString("Id", t.id);
            fragment = new CardDetailFragment();
            fragment.Arguments = bundle;
            FragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, fragment).Commit();

        }

        private async void LoadWishlist()
        {
            string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "database.db3");
            var db = new SQLiteConnection(folder);
            var table = db.Table<Card>();
            _cards = new List<Card>();
            foreach (var card in table)
            {
                _cards.Add(card);
            }
            var adapter = new CardsAdapter(this.Activity, _cards);

            var listViewWishlist = View.FindViewById<ListView>(Resource.Id.ListViewWishlist);

            listViewWishlist.Adapter = adapter;
            listViewWishlist.ItemClick += ListViewCards_ItemClick;

        }
    }
}

xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">



  <ListView
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ListViewWishlist" />
</LinearLayout>

EDIT

Here is a fragment that does work.

fragment :

using System.Collections.Generic;
using System.Threading.Tasks;
using Android.OS;
using Android.Views;
using Android.Widget;
using CardAppReal.Assets;
using CardAppReal.Lib.Models;
using CardAppReal.Lib.Repositories;
using CardAppReal.Lib.Services;
using Fragment = Android.Support.V4.App.Fragment;

namespace NavigationDrawerTest.Fragments
{
    public class SerieFragment : Fragment
    {
        public List<Serie> Series { get; set; }
        public SerieFragment()
        {
            this.RetainInstance = true;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {

            base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.SeriePage, null);
            LoadSeries();

            return view ;
        }

        public void OnBackPressed()
        {
            FragmentManager.PopBackStack();
        }
        private async Task LoadSeries()
        {
            SerieDataService serieDataService = new SerieDataService(new SerieRepo());
            Series = await serieDataService.GetSeriesAsync();
            var context = this.Activity;
            var listViewSeries = View.FindViewById<ListView>(Resource.Id.ListViewSeries);
            listViewSeries.Adapter = new HomeScreenAdapter(context, Series);
            listViewSeries.ItemClick += OnSerieListItemClick;
        }

        private void OnSerieListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Android.Support.V4.App.Fragment fragment = null;
            var listView = sender as ListView;
            var t = Series[e.Position];
            Android.Widget.Toast.MakeText(this.Activity, t.Series, Android.Widget.ToastLength.Short).Show();
            Bundle bundle = new Bundle();
            bundle.PutString("Serie", t.Series);
            fragment = new SetFragment();
            fragment.Arguments = bundle;
            FragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, fragment).Commit();

        }


    }
}

xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ListViewSeries" />
</LinearLayout>

Upvotes: 0

Views: 254

Answers (1)

snachmsm
snachmsm

Reputation: 19253

OnCreateView method invalidate view and return it (with return view;) for add to fragment. you are calling LoadWishlist(); before returning view for adding to Fragment - at this moment your view isn't added anywhere, so you can't use FindViewById (there is no layout)

LoadWishlist(); probably should be called inside OnViewCreated method. or inside OnCreateView you may get reference to ListView and pass to LoadWishlist(ListView listViewWishlist) (and remove var listViewWishlist = View.FindViewById... line then)

Upvotes: 1

Related Questions