Xamarin using C#: System.NullReferenceException: 'Object reference not set to an instance of an object.'
-
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(); } }
-
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(); } }
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.
-
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.
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; }
}
-
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; }
}
-
Sorry, I do not know what that is supposed to mean. You need to trap the actual instruction that throws the exception.
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:
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.
-
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:
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.
-
I have explained why, and how to find the problem. I am afraid I cannot offer any more suggestions.
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
-
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
NB: The
as
operator can and will returnnull
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 useas
when you're not sure whether the object can be converted to the specified type; in which case, you should always check fornull
before using the variable. UsingT y = x as T;
without then checking fory == 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 fornull
, 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 theWebRequest.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