Android - JSON throwing exception - android

So, I have a school project where I have to parse a json array and put the data in a listview.
Here is the json http://demo4404797.mockable.io/speakers
When I run the app, it shows only 5 elements, cause the fifth throws an exception ("org.json.JSONException: No value for Title", and I know the Title is missing. I just want to know to solve this) and the rest of the array elements arent read.
Here is the code:
I've read in other questions that we can use "ourobject.has("whatwewant")" but my teacher says it has to be done other way. Can you help me please?

The sixth item in the JSON you are using does not have the title key.
Since you are not allowed to use "ourobject.has("whatwewant")".
Just replace your code that uses speaker.getString() with this instead:
String name = speaker.optString("Name", "Name NA");
String image= speaker.optString("Image", "Image NA");
The opt method (there are several optString(), optLong(), optBoolean()...) will return the set value if it is available or it will return what ever value you put as a "fallback" if the key is not available.

Since you can't use the jsonObject.has("tag"), you can also break up the try-catch block.
String name;
try {
name = speaker.getString("name");
} catch (Exception e) {
name = ""; // Occurs when it can't find the tag.
}
Repeat this for every field. Please be intentional using this outside of the classroom.

Related

String comparison failure in android when string import from a database

I'm a new one for android developing. I retrieved a string from hosted database. I want to compare that string and set it as a text according to comparison.
if((dataList.get(position).getname()).equals("5b275526bd5600499cce09ae")) {
holder.txtTitle.setText("denim");
}
else {
holder.txtTitle.setText("shirt");
}
}
The retrieved string is "5b275526bd5600499cce09ae". According to this settext should be "denim". But it display as "shirt".
Then I tried the following one
holder.txtTitle.setText(dataList.get(position).getname());
Then it dispayed as 5b275526bd5600499cce09ae". therefore there is no issues to be seen with the retriving value. I can't figure out with what wrong with this.
Please help me to figure out what's wrong with my code as I'm a new one for Android and Java.

Clearer Format Firebase Android retrieved data

When I retrieve my data it contains brackets { and unique id such as - JSDHGJDGJJSKA ... I want to make it cleaner and get rid of the brackets for e.g. my output is:
{-JfFQQRYnhiKeuN5ERGX={msg=Monday},-JfFQAhQQWIFAUuV1nD4={msg=this is test}}
I want to get rid of the brackets and the word msg and retrieve just one of the message at random.
I want my output to be if I pick up a random message:
Monday
if I pick up another at random
this is test
Any ideas on how to achieve this will be greatly appreciated.
This will retrieve a random message from the object you've shown in your question.
function getRandomMessage(data) {
if( !data ) { return null; }
var keys = Object.keys(data);
var randomKey = keys[ Math.floor(Math.random()*keys.length) ];
return data[randomKey];
}
Keep in mind that this assumes you have a small number of records. If you start getting into the thousands, you'll need a more robust solution than just grabbing the entire data set.
When I used this I was able to retrieve my data for eg. I save as Book -> title: "The book of death"
here is the code to retrieve the title:Retrieve data-
String title = (String) snapshot.child("title").getValue();
It worked after I used and I didnt used push since push creates its unique ID and its complex for my level to deal with it so I used:Saving data-
Map<String, Object> title= new HashMap<String, Object>();
title.put("title", "This is a working message");
f.child("Book").updateChildren(title);
and everything worked out. I hope it helps everyone who has having these issues. With update children you can use auto increment for your id.
are you getting data in string ? and If you are using string then it is easy , you can use the method of replace eg: yourString.replace("a","b")

output text line by line

I write app for Android such gets data from server in JSON format. Now I get this value in string, but in my application it must look like:
Route:
1)first point
2)secon point
3).....
n) n point
I read that in Android in textView I can do it if string will be with html tags but I think it is not the best variant. After Android I must do it in iPhone now I don't know how to do that there. Send Routes as Array is not good variant too. Can you say what is the best way to decide this problem?
Have a look here you will have to find the good pattern .
Hence you have separated strings just use a list View with an ArrayAdapter.
I am not so good with regex but i think it should like : [1-9][0-9]) [[a-f][0-9]]+
I couldn't comment b/c of rep, sorry. Could you provide an example of returned JSON string. I think JSON format can be parsed with ease.
If this the case you can parse it in a loop (or another way. I'm not that good at it)
String[] parseIt (String JSON){
String[] list=JSON.split("\\d\\)");
String[] rlist=new String[list.length-1];
for(int i=0;i<list.length-1;i++){
rlist[i]=list[i+1].trim();
}
return rlist;
}
This might do trick. But you should edit result. I didn't test yet
Edit: I edited code. It simply return the address now with leading whitespace. You can get rid off them using. String trim() method like;
list[1].trim();
Do it in loop and don't care about first element (index 0).
Edit 2: Now it should work

How to process an array returned by a wsdl?

I am using ksoap2 in order to extract an array of strings from a wsdl based webservice(for an android app). How do I process the returned array? I need those 3-4 lines of code which will let me save and use that returned array in my class. Thanks.
String r = NameArray.columncount("userid", limitstart, loadNumber,loggername);
String temp = r.replaceAll(";\\s", ",").replaceAll("string=", " ")
.replace("anyType{", "").replace(",}", "");
String[] fulname = temp.split(",\\s+");
'NameArray.columncount' is my function which gets the array from the wsdl(don't get confused in that)
step 1-
Here I am getting the array values returned from the wsdl in to a string called 'r'.In this case I am getting an array of numbers
Returned array string r looks like this
r ="anyType{string=10054; string=10055; string=10056; string=10035; string=10052; string=10036; string=10037; string=10038; }"
step 2-
Then creating a String variable called temp where I am removing all the unwanted characters using the replaceAll function.
after removing unwanted characters temp looks like this
temp="10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038"
step3-
Finally created a string array called 'fulname' and split the modified string with ',\s'
Array fulname after split looks like this
fulname = [ 10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038]
This will work fine because all the wsdl array return the same type of string with same unwanted characters
Hope you understood
Good Luck
If you are still on this problem, you can check out this article which explain the whole procedure to parse arrays returned in KSOAP:
http://seesharpgears.blogspot.fr/2010/10/web-service-that-returns-array-of.html
Hope this answer to your question ;)

Android SDK. String index out of bound exception

I FINALLY have the map and points(arrays) working for my app. Quick question: I have a fatal exception with substring(), a "stringIndexOutOfBoundException"
In general, what is that referring to?
An I going past the end of a string using substring()?
Thanks,
testing.substring(1,2);
(I want to parse each character to find specific characters)
I wouldn't use substring() for grabbing 1-length strings (which is just a single character), but rather charAt(int) for specific positions. If you need to go over all characters in the string, you're probably better off with by converting the whole thing to a char[] first (using toCharArray()) and iterate over that.
Yes, you're going past the end of your strings bounds generally.
The Java API even tells you so...
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing the Strings length and value before attempting substring. That'll help you see the problem.
For example...
String testing = "Hello StackOverflow";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);
Like stated in the official doc here:
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Throws: IndexOutOfBoundsException - if beginIndex is negative or
larger than the length of this String object.

Categories

Resources