JSONException:no value for id - android-studio-2.3

i m using api created in laravel as a url to fetch data from database using xampp server in android studio 2.3.3
using the same wifi source.
checking internet permission
checking code
public void onResponse(JSONObject response)
{
try
{
id.setText(response.getString("id"));
title.setText(response.getString("title"));
body.setText(response.getString("body"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Expected result: the value of id at id textview, value of title at title textview and body value at body textview.
Actual result: I get jsonexception; no value for id

The image below talks about your data structure. Your error is that you are trying to access data in an array without accessing the element inside the array.

Related

How to get a list of files in a directory of a Firebase App in Unity

I am trying to get a list of all files in a directory of the Firebase app. It seems that this is possible on all platforms but Unity. All platforms excluding Unity have an option of "List Files" here. Is there some other way to get a list of all the files?
I also tried to maintain a text file with such entry but it takes a long time to first download the text file, upload the video and again upload the updated text file. (There some other issues as well due to download being async).
Basically my code currently looks like this:
public void UploadVideoandUpdateText()
{
//Downloading Text file
details_text_ref.GetFileAsync(local_text_url).ContinueWith(task => {
if (!task.IsFaulted && !task.IsCanceled)
{
Debug.Log("File downloaded.");
}
});
//Updating local_text_url and downloading it again
details_text_ref.PutFileAsync(local_text_url).ContinueWith((Task<StorageMetadata> task) => {
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = details_text_ref.GetDownloadUrlAsync().ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
//Finally uploading the video
video_ref.PutFileAsync(full_path_video).ContinueWith((Task<StorageMetadata> task) => {
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = video_ref.GetDownloadUrlAsync().ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
}
The above is not working due to the downloads being in async. Is there a solution to make the function wait till the Details txt file is downloaded. Or even better, to have a direct method to view all uploaded files in a directory.
Anyone else coming across this issue, I've managed to find a solution.
Note: This doesn't answer the original question specifically, but general to what the question is asking without any description
How to get all objects within a Firebase folder
Seems easy enough right? Just request to get an object array of the data. Wrong... If the data is kept in a format like this:
Folder
-- 0
---- Name: "Bob"
---- Age: 26
-- 1
---- Name: "Me"
---- Age: 29
-- 2
---- Name: "Jeff"
---- Age: 24
Then it can be retrieved into an object array.
But notice that the sub folders within the folders need to be indexes in order for Firebase to recognize it as an array. This isn't normally how people might keep data. A normal Firebase structure might look like this:
Folder
-- Bob
---- Name: "Bob"
---- Age: 26
-- Me
---- Name: "Me"
---- Age: 29
-- Jeff
---- Name: "Jeff"
---- Age: 24
Notice that now, the sub folders aren't indexed, and so the JSON isn't an array anymore, but another folder. This cannot be read as an array of objects. So what do we do?
We can simply get a dictionary containing keys of type string, and values of type object. This way, we can keep the names of the sub folders, and not have to change them into array index numbers.
However to do this, we need to get the raw JSON first. Here's a way of doing it in C# using a WebClient:
static string GetJson(string url)
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
Debug.Log(json_data);
}
catch (Exception) { }
return json_data;
}
}
The 'url' parameter is the link to our firebase database, alongside our folder name. For example: "https://myprojectid.firebaseio.com/Folder.json". Remember to add .json at the end to get the raw json data.
Next, we need a JSON deserializer to convert our json data into our dictionary. I'm using the Newtonsoft.Json NuGet package, which you can install and place the .dll file into your Assets/Plugins folder. Create it if you haven't already.
Then, to convert it into an object, we just write:
static Dictionary<string, Person> GetObjects(string json)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
return values;
}
This should return a dictionary containing all objects within your folder, hopefully. The object class is called person. Quite simple:
public class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Hopefully this helps someone down the line. Tag me if you have any issues.
Update
There is a much simpler and faster way to do this. I've managed to find an article explaining the usage of a REST API to put and get objects from a Firebase database.
It also explains how to get a collection of objects from a folder using a custom serializer. It's a lot quicker than the WebClient solution above. Here's the link:
Firebase in Unity with REST API
If you use unity after 2017.3 and use .Net 4.x Scripting Backend, use async/await.
Then your code will be like this
public async void UploadVideoandUpdateText()
{
await details_text_ref.GetFileAsync(local_text_url);
var metadata = await details_text_ref.PutFileAsync(local_text_url);
string download_url = (awit details_text_ref.GetDownloadUrlAsync()).ToString();
await video_ref.PutFileAsync(full_path_video);
}
See this article for async / await.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
but in case you can't use async/await, seperate each async operation to function and connect with ContinueWith().
public void UploadVideoandUpdateText()
{
GetFile.ContinueWith(PutText).ContinueWith(PutVideo);
}
private Task GetFile()
{
return details_text_ref.GetFileAsync(local_text_url);
}
private Task<StorageMetadata> GetText()
{
return details_text_ref.PutFileAsync(local_text_url);
}
private Task<StorageMetadata> PutText()
{
return details_text_ref.PutFileAsync(local_text_url);
}
private Task<StorageMetadata> PutVideo()
{
return details_text_ref.PutFileAsync(full_path_video);
}

MVC Post Request how to get Request Content if it's different to that expected by the Default ModelBinder

I have this MVC WebApi action:
PostTrips(List<Trip> trips)
When a list of trips is sent through everything works fine. If, however, someone is trying to post incorrect data, e.g just an object {} then trips is null - this is fine, but I would like to log the data that the user tried to push.
I tried to get it using string requestData = Request.Content.ReadAsStringAsync().Result; but it can only be called once, and I guess the default model binder is calling it to try an map it to my List<Trip>, as when I call it, the result is always null, even though I know I'm passing something in.
Does anyone know of another way to get the posted data again?
I got around this my removing the parameter List<Trip> trips from the action so I had:
public async Task<HttpResponseMessage> PostTrips()
{
}
This bypasses the default model binder and allows you to get the unmodified request content using:
string requestContent = await Request.Content.ReadAsStringAsync();
You can then do what ever you need with this - I wanted to log the data for error tracking.
To create the actual List<Trip> trips I then used Newtonsoft.Json to deserialise the string into a list:
List<TravelTrackerTrip> appTrips = JsonConvert.DeserializeObject<List<TravelTrackerTrip>>(requestContent);
Full example:
public async Task<HttpResponseMessage> PostTrips()
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
List<Trip> appTrips = null;
string requestContent = await Request.Content.ReadAsStringAsync();
try
{
appTrips = JsonConvert.DeserializeObject<List<Trip>>(requestContent);
}
catch(Exception ex)
{
//ERROR LOGGING HERE...
//QUIT - Return failure response
}
try
{
//Success - do whatever we need
}
catch(Exception ex)
{
//ERROR LOGGING HERE...
//QUIT - Return failure response
}
//Return success response
}

How to detect when Vaadin FileDownloader succeeds or fails

I have Vaadin 7 code to give the user an option to download a file:
Button btnDownloadResults = new Button("Download Results", FontAwesome.CLOUD_DOWNLOAD);
resource = new StreamResource(new MyStreamResource(), suggestedSaveAsFilename);
new FileDownloader(resource).extend(btnDownloadResults);
I would like to trigger code when the download has succeeded, or even if the download manages to start. Uses for this include closing a window, starting a progress spinner, or incrementing a download count.
Unlike the Vaadin Upload component, the FileDownloader does not have any listeners for finding out when a file download fails, succeeds, or starts.
Here is a simplified version of my StreamResouce subclass:
public class MyStreamResource implements StreamSource {
#Override
public InputStream getStream() {
String filename = /* code to determine the filename */;
try {
final File results = new File(FilenameUtils.normalize(filename));
return new FileInputStream(results);
} catch (FileNotFoundException fnfe) {
String errorMsg = "Cannot download results. Try again later, or contact your sysadmin.";
Utilities.showError(errorMsg);
return null;
} catch (Exception e) {
Utilities.logAndShowException(e);
return null;
}
}
}
Note that the getStream method returns before the user has even been prompted where to save the file (which they can choose to cancel.) So I can't trigger anything from inside that method.
One suggestion I got was to subclass the FileDownloader as follows:
FileDownloader fileDownloader = new FileDownloader(fileInputStream) {
private static final long serialVersionUID = -4584979099145066535L;
#Override
public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path) throws IOException {
boolean result = super.handleConnectorRequest(request, response, path);
if (result) {
/* YOUR LOGIC GOES HERE */
}
return result;
}
} ;
Again, this fires too soon (and the boolean result is always true, even if my StreamSource returns null.)
Any suggestions?
After more research I believe the answer is that there is no simple way to get this information from the FileDownloader.
The difficulty appears to be a consequence of the way the FileDownloader is designed. From the FileDownloader docs:
"Download should be started directly when the user clicks e.g. a Button without going through a server-side click listener to avoid triggering security warnings in some browsers."
Because there is no round-trip back to the web server, there is no place to respond when the download fails, starts, or succeeds.
Some vague (and possibly bad) ideas for a workaround:
Have JS post some kind of asynchronous notification to the web
server, letting it know what happened. (Using JMS or Ajax?)
If there was some kind active process on the backend involved with transferring the file, it
would know when the transfer happened.
But the short answer seems to be there is no built-in way in Vaadin to do it.

how to bind dynamically image to the windows phone image control

I am consuming .net web-service in my windows phone app.
Here I binding XML data to the controls,I am unable to display image.
C#:
eSchooltrack.ServiceReference5.EST_WebServicesSoapClient obj = new EST_WebServicesSoapClient();
obj.GetLoginUserDetailsCompleted+=new EventHandler<GetLoginUserDetailsCompletedEventArgs>(obj_GetLoginUserDetailsCompleted);
obj.GetLoginUserDetailsAsync(loginid);
}
private void obj_GetLoginUserDetailsCompleted(object sender, eSchooltrack.ServiceReference5.GetLoginUserDetailsCompletedEventArgs e)
{
XElement xmlNews = XElement.Parse(e.Result.ToString());
image1.Source=GetImage(xmlNews.Element("ProfileImage").Value);
}
depending upon the return type of the GetImage function
1) if its BitmapImage, then it should work, else the Image its returning is null
2) if its Uri do image1.Source=new BitmapImage(GetImage(xmlNews.Element("ProfileImage").Value));
3) if its a string do image1.Source=new BitmapImage(new Uri(GetImage(xmlNews.Element("ProfileImage").Value)));
I hope it helps. Do note, if still the image is not being displayed, you should check the returning value of the function != null before assigning it.

ASP.NET MVC - Proper way to handle ajax actions with no return object

I have a controller action that does some work in the database and then exits when it's finished. This action is being called via jQuery's ajax function with the dataType set to 'json'.
If I set the return type of the action to void, everything will function just fine except Firefox will show an error in the console that says: "no element found".
It makes sense that Firefox would throw this error if it was expecting XML to come back. However, even when I change the dataType property of the ajax call to "text", I still receive the error. In order to get rid of the error with the return type void, I would have to set the Response's ContentType to "text/html". Or I could set the return type to JsonResult and return a new [empty] JsonResult object.
I'm sure there are several ways I can make this error go away, but I wanted to know the proper way to handle actions with no return values being called via ajax.
If it matters, I'm also using the async controller action pattern.
public void DoSomethingAsync(SomeJsonObjectForModelBinding model)
{
// do some database things
}
public void DoSomethingCompleted()
{
// nothing to do...
// what should my return type be?
// do I need to set the content type here?
}
I know this doesn't exactly answer your question, but I would argue that you should always have a return value coming back from an AJAX or web service call. Even if only to tell you that the operation was successful, or otherwise return the error (message) back to you.
I often define a class like this:
public class JsonResultData
{
private bool _success = true;
public bool Success
{
get { return _success; }
set { _success = value; }
}
public object Value { get; set; }
public List<string> Errors { get; set; }
public JsonResultData()
{
this.Errors = new List<string>();
}
}
And then use it to return data or any other call meta data in the JsonResultData wrapper like so:
return new JsonResult {
Data = new JsonResultData { Value = returnValue, Success = true }
};
I can't comment because of my reputation but I still wanted to contribute to clear the confusion in Kon's answer.
In an application I caught all exceptions within an ActionMethod, set an HttpStatusCode and added an error message to the response. I extracted the message in the Ajax error function and showed it to the user.
Everything worked out fine until the application got put on the staging server, who had some kind of settings that did not allow a return message within an erroneous response. Instead some standard Html was transmitted resulting in a JS error processing the response.
In the end I had to rewrite all my exception handling returning my application errors as successful Ajax call (which it actually is) and then differ within the Ajax success function, just the way it should be.
You should not mix system-level and application-level feedback. You may not be able to control the system-level feedback the way your application needs.

Resources