Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Mobile Development
  3. Mobile
  4. Xamarin using C#: System.NullReferenceException: 'Object reference not set to an instance of an object.'

Xamarin using C#: System.NullReferenceException: 'Object reference not set to an instance of an object.'

Scheduled Pinned Locked Moved Mobile
csharpphpmobilejsonhelp
8 Posts 3 Posters 18 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    Luis M Rojas
    wrote on last edited by
    #1

    Hello, I am new in XAMARIN, i have a simple APP in VS2022. Here is part of the code:

    public interface IRepository
    {
    [Get("/package/")]
    Task GetAllData();
    }

    public class PaqueteServicio
    {
    public const string API_BASE_URL = "http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221";

        private IRepository repo;
        public PaqueteServicio()
        {
            repo = RestService.For(API\_BASE\_URL);
        }
        public Task Get()
        {
            return repo.GetAllData();
        }
    }
    

    Package.cs

    public class Package
    {      
            \[JsonProperty("peso")\]
            public string Peso { get; set; }
    
            \[JsonProperty("tracking\_number")\]
            public string TrackingNumber { get; set; }
    
            \[JsonProperty("contenido")\]
            public string Contenido { get; set; }
    

    public class Resultado
    {
    [JsonProperty("results")]
    public Package[] Results { get; set; }
    }

    Main:

    class MainViewModel : BaseViewModel
    {
    private readonly PaqueteServicio paqueteServicio;
    private List paqueteList;
    public List PaqueteList
    {
    get => paqueteList;
    set
    {
    paqueteList = value;
    RaisePropertyChanged();
    }
    }
    public ICommand ClickCommand => new Command(ClickCommandExecute);

        private async void ClickCommandExecute()
        {
            var response= await paqueteServicio.Get();  **//This line is the one with the Error**
            PaqueteList = response.Results.ToList();
        }
    
        public MainViewModel()
        {
            paqueteServicio = new PaqueteServicio();
        }
    }
    
    L 1 Reply Last reply
    0
    • L Luis M Rojas

      Hello, I am new in XAMARIN, i have a simple APP in VS2022. Here is part of the code:

      public interface IRepository
      {
      [Get("/package/")]
      Task GetAllData();
      }

      public class PaqueteServicio
      {
      public const string API_BASE_URL = "http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221";

          private IRepository repo;
          public PaqueteServicio()
          {
              repo = RestService.For(API\_BASE\_URL);
          }
          public Task Get()
          {
              return repo.GetAllData();
          }
      }
      

      Package.cs

      public class Package
      {      
              \[JsonProperty("peso")\]
              public string Peso { get; set; }
      
              \[JsonProperty("tracking\_number")\]
              public string TrackingNumber { get; set; }
      
              \[JsonProperty("contenido")\]
              public string Contenido { get; set; }
      

      public class Resultado
      {
      [JsonProperty("results")]
      public Package[] Results { get; set; }
      }

      Main:

      class MainViewModel : BaseViewModel
      {
      private readonly PaqueteServicio paqueteServicio;
      private List paqueteList;
      public List PaqueteList
      {
      get => paqueteList;
      set
      {
      paqueteList = value;
      RaisePropertyChanged();
      }
      }
      public ICommand ClickCommand => new Command(ClickCommandExecute);

          private async void ClickCommandExecute()
          {
              var response= await paqueteServicio.Get();  **//This line is the one with the Error**
              PaqueteList = response.Results.ToList();
          }
      
          public MainViewModel()
          {
              paqueteServicio = new PaqueteServicio();
          }
      }
      
      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Very interesting but you forgot to ask a question. The message you see is telling you that you are trying to use a reference variable that does not have a value. This could be because you forgot to initialise it, or because some method call has not returned the reference that you expected. But either way the only way to find the offending code (and fix it) is to use the debugger and trace what your code is doing.

      L 1 Reply Last reply
      0
      • L Lost User

        Very interesting but you forgot to ask a question. The message you see is telling you that you are trying to use a reference variable that does not have a value. This could be because you forgot to initialise it, or because some method call has not returned the reference that you expected. But either way the only way to find the offending code (and fix it) is to use the debugger and trace what your code is doing.

        L Offline
        L Offline
        Luis M Rojas
        wrote on last edited by
        #3

        Thanks at lot, Well, after debuggin i got this message, maybe this is really the PROBLEM:

        //After debugin i can see this error: id=1 Status =WaitingForActivation, Method={null},

        I had read the possible solutions: But i do not get it. Sorry. Here is the code

        As soon the App starts this method is executed:
        public PaqueteServicio()
        {
        repo = RestService.For(API_BASE_URL);

            }
        

        and var repo get the URL value

        When clicked the button: This is executed

        public Task Get()
        {
        return repo.GetAllData();
        //After debugin i can see this error: id=1 Status =WaitingForActivation, Method={null},
        }

        Which it was defined here:
        public interface IRepository
        {
        [Get("/")]
        Task GetAllData();
        }

        Where Resultado is this (a class)

        public class Resultado
        {
            \[JsonProperty("results")\]
            public Package\[\] Results { get; set; }
        }
        

        And Package is my json file:

        public class Package
        {

            \[JsonProperty("peso")\]
            public string Peso { get; set; }
        
            \[JsonProperty("tracking\_number")\]
            public string TrackingNumber { get; set; }
        
            \[JsonProperty("contenido")\]
            public string Contenido { get; set; }
        

        }

        L 1 Reply Last reply
        0
        • L Luis M Rojas

          Thanks at lot, Well, after debuggin i got this message, maybe this is really the PROBLEM:

          //After debugin i can see this error: id=1 Status =WaitingForActivation, Method={null},

          I had read the possible solutions: But i do not get it. Sorry. Here is the code

          As soon the App starts this method is executed:
          public PaqueteServicio()
          {
          repo = RestService.For(API_BASE_URL);

              }
          

          and var repo get the URL value

          When clicked the button: This is executed

          public Task Get()
          {
          return repo.GetAllData();
          //After debugin i can see this error: id=1 Status =WaitingForActivation, Method={null},
          }

          Which it was defined here:
          public interface IRepository
          {
          [Get("/")]
          Task GetAllData();
          }

          Where Resultado is this (a class)

          public class Resultado
          {
              \[JsonProperty("results")\]
              public Package\[\] Results { get; set; }
          }
          

          And Package is my json file:

          public class Package
          {

              \[JsonProperty("peso")\]
              public string Peso { get; set; }
          
              \[JsonProperty("tracking\_number")\]
              public string TrackingNumber { get; set; }
          
              \[JsonProperty("contenido")\]
              public string Contenido { get; set; }
          

          }

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          Sorry, I do not know what that is supposed to mean. You need to trap the actual instruction that throws the exception.

          L 1 Reply Last reply
          0
          • L Lost User

            Sorry, I do not know what that is supposed to mean. You need to trap the actual instruction that throws the exception.

            L Offline
            L Offline
            Luis M Rojas
            wrote on last edited by
            #5

            Well, I just changed the code complete:

            async void Button_Clicked(System.Object sender, System.EventArgs e)
            {
            var httpClient = new HttpClient();
            var resultJson = await httpClient.GetStringAsync("http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221");

                    var resultList = JsonConvert.DeserializeObject(resultJson);
            
                    PaqueteList.ItemsSource = resultList;
                }
            

            And Package is my json file:

            public class Package
            {

                \[JsonProperty("peso")\]
                public string Peso { get; set; }
            
                \[JsonProperty("tracking\_number")\]
                public string TrackingNumber { get; set; }
            
                \[JsonProperty("contenido")\]
                public string Contenido { get; set; }
            

            }

            If you use postman and type the URL:

            "http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221"

            You got an answer, but not in the programa, if it the same Error: Object Set without... and it is correct because there is not answer, But WHY? because it is works on postman.

            L 1 Reply Last reply
            0
            • L Luis M Rojas

              Well, I just changed the code complete:

              async void Button_Clicked(System.Object sender, System.EventArgs e)
              {
              var httpClient = new HttpClient();
              var resultJson = await httpClient.GetStringAsync("http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221");

                      var resultList = JsonConvert.DeserializeObject(resultJson);
              
                      PaqueteList.ItemsSource = resultList;
                  }
              

              And Package is my json file:

              public class Package
              {

                  \[JsonProperty("peso")\]
                  public string Peso { get; set; }
              
                  \[JsonProperty("tracking\_number")\]
                  public string TrackingNumber { get; set; }
              
                  \[JsonProperty("contenido")\]
                  public string Contenido { get; set; }
              

              }

              If you use postman and type the URL:

              "http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221"

              You got an answer, but not in the programa, if it the same Error: Object Set without... and it is correct because there is not answer, But WHY? because it is works on postman.

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              I have explained why, and how to find the problem. I am afraid I cannot offer any more suggestions.

              L 1 Reply Last reply
              0
              • L Lost User

                I have explained why, and how to find the problem. I am afraid I cannot offer any more suggestions.

                L Offline
                L Offline
                Luis M Rojas
                wrote on last edited by
                #7

                Solution: I just changed the code to:

                HttpWebRequest wReq = WebRequest.Create("http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221") as HttpWebRequest;
                string json = null;
                using (HttpWebResponse wResp =(HttpWebResponse) wReq.GetResponse())
                {
                using (Stream s = wResp.GetResponseStream())
                {
                using (TextReader tr = new StreamReader(s))
                {
                json = tr.ReadToEnd();
                MessageBox.Show(json);
                }
                }
                }

                and i can read the URL without problem

                Richard DeemingR 1 Reply Last reply
                0
                • L Luis M Rojas

                  Solution: I just changed the code to:

                  HttpWebRequest wReq = WebRequest.Create("http://www.mi.traelopaq.net/listarpaqjson.php?text1=2264&text2=pOADSIQMASD.O398AJas&KEYAPI=ODUTRAS.9di23821@ldpli2skjs43&KEYPASo=OASmsjdu38IO1p29AA93JA0OD9K1221") as HttpWebRequest;
                  string json = null;
                  using (HttpWebResponse wResp =(HttpWebResponse) wReq.GetResponse())
                  {
                  using (Stream s = wResp.GetResponseStream())
                  {
                  using (TextReader tr = new StreamReader(s))
                  {
                  json = tr.ReadToEnd();
                  MessageBox.Show(json);
                  }
                  }
                  }

                  and i can read the URL without problem

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  NB: The as operator can and will return null if the object you're trying to cast cannot be converted to the target type. Type-testing operators and cast expression - C# reference | Microsoft Docs[^] You use as when you're not sure whether the object can be converted to the specified type; in which case, you should always check for null before using the variable. Using T y = x as T; without then checking for y == null is always a mistake. When you're certain that the object will be of the desired type, you use a cast expression instead: T y = (T)x; In this case, there is no need to check for null, since the runtime would throw an exception if the conversion cannot be performed. However, in this case, it would be far better to simply use the WebRequest.CreateHttp method, which has been available since .NET 4.5, and already returns the correct type: WebRequest.CreateHttp Method (System.Net) | Microsoft Docs[^]


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups