Comma is causing unwanted string split - java

I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:
public List getAnswerStringEdit() {
return answer_edit;
}
I save it as so:
editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
Then retrieve it here:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
answerString = answerString.substring(1, answerString.length() - 1).trim();
String[] array = answerString.split(",");
Finally, I access the array as so:
et_answer1_edit.append(array[0]);
My problem is this - Say I add a questions which has a comma in the middle of it, like -
Question 1- "Why is this broke, I don't know?"
Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:
"Why is this broke, I don't know?"
However, instead I am getting in position 0:
Why is this broke - then position 1 as: I don't know
I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.
The retrieved JSON is as follows:
{
"result": "success",
"message": "Answer Has Been Selected",
"answer": {
"answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
}
}
Any help/advice that can help me to understand what is causing this, would be really appreciated.

Dont split the string using ',' use this
JSONObject jsonObject = new JSONObject(answerString );
JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
String QuestionString1 = jsonArray.get(0).toString();
String QuestionString2 = jsonArray.get(1).toString();

try this one
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject answer= jsonObject.getJSONObject("answer");
JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArrayAnswerEdit);
for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
String que= jsonArrayAnswerEdit.getString(i);
Log.e("json", i + "=" + que);
}
} catch (JSONException e) {
e.printStackTrace();
}

Try this
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject data = jsonObject.getJSONObject("answer");
JSONArray jsonArray = data.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArray);
for (int i = 0; i < jsonArray.length(); i++)
{
String value = jsonArray.getString(i);
String[] parts = value.split(Pattern.quote(","));
for (int j=0; j<parts.length; j++)
{
Log.e("Answer String ", "=" + parts[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
E/=>: ["Why is this broke, I don't know?","What is your favorite song, because I want to know"]
E/Answer String: =Why is this broke
E/Answer String: = I don't know?
E/Answer String: =What is your favorite song
E/Answer String: = because I want to know

After reading all the suggest answers, figured out a simple solution:
First I stored my answers sent from my external database as so -
final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
Then saved in shared pref -
editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
Next to read the answer back out:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
Finally, I could set my Edittext with data from the array:
et_answer1_edit.append(array[0].trim());
et_answer2_edit.append(array[1].trim());

Related

JSON Reading Object Values

I have a JSON response from Spotify that I'm trying to read from. And in my java code I am getting the 'name' value for the album object, and not for the tracked object. Here is the response: https://pastebin.com/fcvTzJJv
Towards the bottom of the JSON Response, there is a name field that says "Money in the Grave", that is what I want to get from the JSON, instead of "The Best in the world pack" which is under the name of the album.
Here is the code that reads this response:
try
{
JSONObject obj = new JSONObject(result);
JSONObject tracks = obj.getJSONObject("tracks");
JSONArray items = tracks.getJSONArray("items");
for(int i = 0; i < items.length(); i++)
{
//album object
JSONObject album = items.getJSONObject(i).getJSONObject("album");
//SHOULD be getting the images array but does not
//artist array
JSONArray artists = album.getJSONArray("artists");
//gets the necessary artist information
for(int j = 0; j < artists.length(); j++)
{
JSONObject artist = artists.getJSONObject(j);
songLists.add(artist.getString("name") + " - " +album.getString("name"));
}
}
}
With the above code, I'm getting "The Best in the World Pack", and not "Money in the Grave". Could someone help explain how to get the track's name, and not the albums name. Thanks
for(int i = 0; i < items.length(); i++)
{
JSONObject values = items.getJSONObject(i);
String name= values.getString("name");
System.out.println(name+" nameee");
//artist array
JSONArray artists = album.getJSONArray("artists");
}
this will work for you and will return "Money In The Grave (Drake ft. Rick Ross)"
You can try like this and it will give that track name
String response = yourJSonData;
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("data","data---"+response);
JSONArray jsArrItems = jsonObject.getJSONObject("tracks").getJSONArray("items");
Log.e("data","data---222>>"+jsArrItems.getJSONObject(0).getString("name")+"<<>>"+jsArrItems);
} catch (JSONException e) {
e.printStackTrace();
}
If you have items as JSONArray more than 1 then can use the loop as well
get name like tems.getJSONObject(i).getString("name") in your items loop as name you are looking is in items array object not in artist object.

Java - JSONArray has 10 objects but only display first two

I'm new to Android and Java so I'm building a demo app of book listing to learn about parsing JSON data. I use log to check how many books there are on data (which is 10 ) but only get 2 first books on the list displayed when running it on an emulator... Hope anyone can tell me where I should change?
Thanks for any opinion!
E/QueryUtils: length of array: 10
The API link: https://www.googleapis.com/books/v1/volumes?q=search+terms
QueryUtils.java
private static List<BookItem> extractItemFromJson(String bookJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(bookJSON)){
return null;
}
// Create an empty ArrayList that we can start adding books to
List<BookItem> bookItems = new ArrayList<>();
// Try to parse the JSON response string. If there is a problem with the way the JSON is formatted,
// a JSONException exception object will be thrown.
// Catch the exception so the app doesnt crash, and prent the error message to the logs.
try {
JSONObject baseJsonresponse = new JSONObject(bookJSON);
JSONArray bookItemArray = baseJsonresponse.getJSONArray("items");
Log.e("QueryUtils", "length of array: " + bookItemArray.length());
for (int i = 0; i < bookItemArray.length(); i++) {
JSONObject currentBook = bookItemArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
String title = volumeInfo.getString("title");
String subtitle = volumeInfo.getString("subtitle");
String previewLink = volumeInfo.getString("previewLink");
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
String thumbnail = imageLinks.getString("smallThumbnail");
BookItem book = new BookItem(/**author, */title, subtitle, thumbnail, previewLink);
bookItems.add(book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
return bookItems;
}
The third book in your list does not cointain the field imageLinks, and that causes an exception.
You should add a check:
String thumbnail = "";
if (volumeInfo.has("imageLinks")) {
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
thumbnail = imageLinks.getString("smallThumbnail");
}
I suspect it's going to the catch block after parsing the first 2 because an exception happened while parsing, You should fix the exception and also you can catch the exception inside the loop to add the items that could be parsed and don't quit the loop if there is a JSONException.

Reading JSON from Java

I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.

android error when trying to put json data in viewlist php+json+java

I am trying to make a search page for my andriod app using PHP,JSON and SQL.
here is the code that is giving me the error :
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
tempID += json_data.getString("ID") + "\n";
tempID += json_data.getString("heading") + "\n";
tempID += json_data.getString("rank") + "\n:";
}
arr = tempID.split(":");
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
}catch (Exception e){
String errMsg = "error when putting the json data in the list";
Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
}
i have already used this code on another page and it works perfectly but when using it another page/activity it gives me an error when trying to put the json data in listview.
i would guess the problem is when i am setting the ArrayAdapter, have i done anything wrong?
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,arr));
To answer your final question:
//array list
List<String> your_array_list = new ArrayList<String>();
try{
JSONArray jArray = new JSONArray(result);
int jArrLeng = jArray.length();
for(int i=0; i<jArrLeng;i++){
JSONObject json_data= jArray.getJSONObject(i);
your_array_list.add(json_data.getString("ID") + "\n");
your_array_list.add(json_data.getString("heading") + "\n");
your_array_list.add(json_data.getString("rank") + "\n:");
}
resultLV.setAdapter(new ArrayAdapter<String>(SearchPage.this, android.R.layout.simple_list_item_1,your_array_list));
//then, to get the items from inside the adapter:
for(String item_in_list : your_array_list){
System.out.println(item_in_list);
}
To answer the original question:
Check out http://jsonformatter.curiousconcept.com/ for formatting issues
Try looking at this info:
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
FYI: The inbuilt JSONObject and JSONArray cannot be used to get certain json responses.
You could try downloading a small library named "json-simple-1.1.1.jar" from this link https://json-simple.googlecode.com/files/json-simple-1.1.1.jar.

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Categories