简体   繁体   中英

Cannot access a nonstatic member of outer type… via nested type

Why do I get this error?

Error CS0038: Cannot access a nonstatic member of outer type JsonFeedParserTabs.MainActivity' via nested type JsonFeedParserTabs.MainActivity.SampleTabFragment' (CS0038) (JsonFeedParserTabs)

I'm trying to put a ListView with json data inside a tab.

This is my code:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Linq;

namespace JsonFeedParserTabs
{
    [Activity (Label = "Feed Reader", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        ListView listView;
//      ProgressBar progressBar;
        RootObject result;

        string url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource.
            SetContentView (Resource.Layout.Main);

            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;

            AddTab (" Tab 1", new SampleTabFragment ());
//          AddTab (" Tab 2", new SampleTabFragment2 ());

            if (bundle != null)
                this.ActionBar.SelectTab(this.ActionBar.GetTabAt(bundle.GetInt("tab")));
        }

        protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex);

            base.OnSaveInstanceState(outState);
        }

        void AddTab (string tabText, Fragment view)
        {
            var tab = this.ActionBar.NewTab ();

            tab.SetText (tabText);

            // Must set event handler before adding tab.
            tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add (Resource.Id.fragmentContainer, view);
            };
            tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs e) {
                e.FragmentTransaction.Remove(view);
            };

            this.ActionBar.AddTab (tab);
        }

        class SampleTabFragment : Fragment
        {
            public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                base.OnCreateView (inflater, container, savedInstanceState);

                var view = inflater.Inflate (Resource.Layout.Tab, container, false);

                // Initializing listView.
                listView = view.FindViewById<ListView> (Resource.Id.listView); // <-- Error!
                listView.ItemClick += OnListItemClick; // <-- Error!

//              progressBar = view.FindViewById<ProgressBar> (Resource.Id.progressBar);
//  
//              // Showing loading progressBar.
//              progressBar.Visibility = ViewStates.Visible;

                // Download and display data in url.
                downloadJsonFeedAsync (url); // <-- Error!

                return view;
            }
        }

//      class SampleTabFragment2 : Fragment
//      {
//          public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//          {
//              base.OnCreateView(inflater, container, savedInstanceState);
//
//              var view = inflater.Inflate(Resource.Layout.Tab, container, false);
//              var sampleTextView = view.FindViewById<TextView>(Resource.Id.sampleTextView);
//
//              sampleTextView.Text = "Sample fragment text 2.";
//
//              return view;
//          }
//      }

        public async void downloadJsonFeedAsync(String url)
        {
            var httpClient = new HttpClient();
            Task<string> contentsTask = httpClient.GetStringAsync(url);

            // Await! control returns to the caller and the task continues to run on another thread.
            string content = await contentsTask;
            Console.Out.WriteLine("Response Body: \r\n {0}", content);

            // Convert string to JSON object.
            result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (content);

            // Update listview.
            RunOnUiThread (() => {
                listView.Adapter = new CustomListAdapter(this, result.posts);
//              progressBar.Visibility = ViewStates.Gone;
            });
        }

        void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Post item = result.posts.ElementAt (e.Position);

            // Passing object form one activity to other.
            Intent i = new Intent(Application.Context, typeof(FeedDetailsActivity));
            i.PutExtra("item", JsonConvert.SerializeObject(item));
            StartActivity(i);
        }
    }
}

I'm stuck and need help, any ideas what I have done wrong and what to do? Thank you!

Update

Alright it works now but i think there might be a better way to do this.

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Linq;

namespace JsonFeedParserTabs
{
    [Activity (Label = "Feed Reader", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        ListView listView;
//      ProgressBar progressBar;
        RootObject result;

        string url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource.
            SetContentView (Resource.Layout.Main);

            this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;

            AddTab (" Tab 1", new SampleTabFragment (this));
//          AddTab (" Tab 2", new SampleTabFragment2 ());

            if (bundle != null)
                this.ActionBar.SelectTab(this.ActionBar.GetTabAt(bundle.GetInt("tab")));
        }

        protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex);

            base.OnSaveInstanceState(outState);
        }

        void AddTab (string tabText, Fragment view)
        {
            var tab = this.ActionBar.NewTab ();

            tab.SetText (tabText);

            // Must set event handler before adding tab.
            tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) {
                var fragment = this.FragmentManager.FindFragmentById(Resource.Id.fragmentContainer);

                if (fragment != null)
                    e.FragmentTransaction.Remove(fragment);

                e.FragmentTransaction.Add (Resource.Id.fragmentContainer, view);
            };
            tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs e) {
                e.FragmentTransaction.Remove(view);
            };

            this.ActionBar.AddTab (tab);
        }

        class SampleTabFragment : Fragment
        {
            private MainActivity context;
            public SampleTabFragment(MainActivity _context) : base()
            {
                this.context = _context;
            }

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

                var view = inflater.Inflate (Resource.Layout.Tab, container, false);

                // Initializing listView.
                context.listView = view.FindViewById<ListView> (Resource.Id.listView);
                context.listView.ItemClick += context.OnListItemClick;

//              progressBar = view.FindViewById<ProgressBar> (Resource.Id.progressBar);
//  
//              // Showing loading progressBar.
//              progressBar.Visibility = ViewStates.Visible;

                // Download and display data in url.
                context.downloadJsonFeedAsync (context.url);

                return view;
            }
        }

//      class SampleTabFragment2 : Fragment
//      {
//          public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//          {
//              base.OnCreateView(inflater, container, savedInstanceState);
//
//              var view = inflater.Inflate(Resource.Layout.Tab, container, false);
//              var sampleTextView = view.FindViewById<TextView>(Resource.Id.sampleTextView);
//
//              sampleTextView.Text = "Sample fragment text 2.";
//
//              return view;
//          }
//      }

        public async void downloadJsonFeedAsync(String url)
        {
            var httpClient = new HttpClient();
            Task<string> contentsTask = httpClient.GetStringAsync(url);

            // Await! control returns to the caller and the task continues to run on another thread.
            string content = await contentsTask;
            Console.Out.WriteLine("Response Body: \r\n {0}", content);

            // Convert string to JSON object.
            result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (content);

            // Update listview.
            RunOnUiThread (() => {
                listView.Adapter = new CustomListAdapter(this, result.posts);
//              progressBar.Visibility = ViewStates.Gone;
            });
        }

        void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Post item = result.posts.ElementAt (e.Position);

            // Passing object form one activity to other.
            Intent i = new Intent(Application.Context, typeof(FeedDetailsActivity));
            i.PutExtra("item", JsonConvert.SerializeObject(item));
            StartActivity(i);
        }
    }
}

It's telling you exactly what it can't do. The MainActivity members are not accessible from the fragment types declared within the MainActivity type. So when you try to call downloadJsonFeedAsync (url); it fails because it's not a static (class) method. The fragments (although declared within the type), do not exist within an instance of the MainActivity type.

Unless there's some compelling reason for them to remain within the MainActivity type, I'd move them out. They should also then have a reference to the MainActivity type so that you can call downloadJsonFeedAsync(string) on it.

On an unrelated note (and I appreciate this is very much uninvited commentary :) ), you may want to consider using a MVVM pattern. It looks like you're intermixing presentation, application control, and business data. If this app grows beyond the one or two pages, you will find much peace in segregating responsibilities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM