Android setText in for loop to hold JsonObject values overwriting itself - java

I have been fiddling with this for a few hours, essentially what I am trying to do is create a JsonObject and get it's value inside a for loop and Set it to a TextView. It is working however I am getting only the Second loop values, to clarify this is the output from my JsonObject
{"Areas":[{"City":"Dallas","State":"Texas"},{"City":"Seattle","State":"Washington"}]}
However I am only getting {"City":"Seattle","State":"Washington"} the second values in the loop inside my Textviews setText. I would like to get both the first and second loop inside my Textview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystates);
try {
// Create my Json Array
JSONObject newJsonObject = new JSONObject();
JSONArray myarray = new JSONArray();
JSONObject states= new JSONObject();
states.put("City", "Dallas");
states.put("State", "Texas");
JSONObject states2= new JSONObject();
states2.put("City", "Seattle");
states2.put("State", "Washington");
myarray.put(states);
myarray.put(states2);
newJsonObject.put("Areas", array);
// Ends Json Array
//set Textviews
TextView citiess = (TextView)findViewById(R.id.citiess);
TextView statess = (TextView)findViewById(R.id.statess);
String cityString="";
String stateString="";
// retrieve Json Array and set For Loop
JSONArray jaLocalstreams = names.getJSONArray("Areas");
for(int position=0;position<jaLocalstreams.length();position++)
{
JSONObject JO = jaLocalstreams.getJSONObject(position);
cityString= JO.getString("City");
stateString = JO.getString("State");
citiess.setText(""+cityString);
statess.setText(""+stateString);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I have pretty much narrowed down the problem area and I think it is this
citiess.setText(""+cityString);
statess.setText(""+stateString);
setText is replacing the values with the newest ones which makes sense, how can I change this so that it does not do that? When I put this in the for loop
System.err.println(cityString+","+stateString);
I get both loop values of Dallas,Texas and Seattle,Washington. Which is why I am sure that setText is the issue any suggestions would be great.

Its seems that cityString,stateString get overwrite on loop and setText will print last value only.Therfore you need to append json values in string and then set those values after loop as
for (int position = 0; position < jaLocalstreams.length(); position++) {
JSONObject JO = jaLocalstreams.getJSONObject(position);
cityString += JO.getString("City");
stateString += JO.getString("State");
}
citiess.setText("" + cityString);
statess.setText("" + stateString);

Related

Comma is causing unwanted string split

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());

How to Parse REST API with three possible variations in Android

I am trying to parse a REST API that has 3 possible variations. The first one is the one I already have working where there is an array for the "row" output as shown in the photo below.
There is also row as an object, as pictured below.
And finally, one where there is no data, as shown below.
Any one of these is a possible output when parsing the API, I need something like an if statement to see which one is the output and parse the information from there, but I do not know how to create an if statement for this particular need. Here is my current code:
JSONObject parentObject = new JSONObject(finalJson);
JSONObject responseJSON = JSONUtils.jsonObjectFromJSONForKey(parentObject, "response");
if (responseJSON != null) {
JSONObject resultJSON = JSONUtils.jsonObjectFromJSONForKey(responseJSON, "result");
JSONObject contactsJSON = JSONUtils.jsonObjectFromJSONForKey(resultJSON, "Potentials");
JSONArray parentArray = contactsJSON.getJSONArray("row");
List<Photoshoots> photoshootsList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject mainObject = parentArray.getJSONObject(i);
JSONArray mainArray = mainObject.getJSONArray("FL");
Photoshoots photoshoot = new Photoshoots();
...
I have solved the problem I was having. It may not be the ideal way to solve the problem, but it does work. Inside of the doInBackground in AsyncTask, I had initially converted the JSON result data into a StringBuffer, then converted the StringBuffer to a String. I then used one if and 2 else if statements to parse the data. The first if statement checks if the JSON string contains the phrase "nodata" representing that no data matches my original criteria, shown below:
if (finalJson.contains("nodata"))
I then had it pass on null data to be checked in onPostExecute for later. Next else if statement checked to see if row is an array. The way I did that was check to see if the string had a [ after row, indicating that it was an array, shown below:
else if (finalJson.contains("{\"response\":{\"result\":{\"Potentials\":{\"row\":["))
I then parsed the information as follows:
JSONArray parentArray = contactsJSON.getJSONArray("row");
for (int i = 0; i < parentArray.length(); i++) {
JSONObject mainObject = parentArray.getJSONObject(i);
JSONArray mainArray = mainObject.getJSONArray("FL");
the final else if, which could probably just be an else statement, is almost the same, except looking for a { after row instead of [, indicating it was just an object, as shown below:
else if (finalJson.contains("{\"response\":{\"result\":{\"Potentials\":{\"row\":{"))
I then parsed the information as follows:
JSONObject mainObject = contactsJSON.getJSONObject("row");
JSONArray mainArray = mainObject.getJSONArray("FL");
Inside of the onPostExecute, I have a code that will run a class that extends ArrayAdapter for the results contained in both of the else if statements, but I don't want it to run if there is no data, so I did the following:
protected void onPostExecute(List<Photoshoots> result) {
super.onPostExecute(result);
if (result != null) {
PhotoshootAdapter adapter = new PhotoshootAdapter(getApplicationContext(), R.layout.row, result);
lvPhotoshoots.setAdapter(adapter);}
else{
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
btnRefresh.setText("No Data to Show. Try again in " + millisUntilFinished / 1000 + " Seconds");
}
public void onFinish() {
btnRefresh.setText("Refresh");
btnRefresh.setEnabled(true);
}
}.start();
The result will pass the null data if there is nodata, but a list if there is data within the result. Like I said, there may be a better way to solve this problem, but the app works now and it doesn't crash regardless of the data that is returned.

JSON Parse to Array value not appended properly

I have an array String[] cruce_no.I am appending Values from JSON response to the array. JSON response is a,b,c .... I need to append value Select to the 0th position of Array 'cruce_no'.
I need result like this {Select,a,b,c...}. But I am getting like this {Select,b,c...}. My code is below:
JSONArray JA=new JSONArray(result);
JSONObject json= null;
cruce_no = new String[JA.length()];
name = new String[JA.length()];
cruce_no[0] = "Select";
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
cruce_no[i] = json.getString("
}
How can I solve this? Please help me.
Increase the size of the array by 1
cruce_no = new String[JA.length()+1];
cruce_no[0] = "Select";
Inside the forloop use this
cruce_no[i+1] = json.getString("YOUR_KEY");
You getting {Select,b,c...} instead of {Select,a,b,c...} because you add Select at 0th position so "a" replaced by "Select"
try like this
JSONArray JA=new JSONArray(result);
JSONObject json= null;
cruce_no = new String[JA.length()+1];
name = new String[JA.length()];
cruce_no[0] = "Select";
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
cruce_no[i+1] = json.getString("
}
Make array size new String[JA.length()+1] as you are going to add an extra element select in it. And then place select at 0th positon followed by rest of the elements. So 0th position should not be overwritten.

Error when using JSONSimple to write a json file with for loop

I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17.
Here is my code:
JSONObject jsonObject = new JSONObject();
JSONObject jsonNodesObject = new JSONObject();
JSONObject jsonEdgesObject = new JSONObject();
JSONArray jsonNodesArray = new JSONArray();
JSONArray jsonEdgesArray = new JSONArray();
String instString = solutions.get(0).get("institution");
jsonNodesObject.put("name", instString);
// extract name and institution from ArrayList
for (int i = 0; i < solutions.size(); i++)
{
HashMap<String, String> eleHashMap= solutions.get(i);
String nameString = eleHashMap.get("name");
jsonNodesObject.put("name", nameString);
jsonNodesArray.add(jsonNodesObject);
jsonEdgesObject.put("source", 0);
jsonEdgesObject.put("target", i);
jsonEdgesArray.add(jsonEdgesObject);
}
jsonObject.put("nodes", jsonNodesArray);
jsonObject.put("edges", jsonEdgesArray);
System.out.println(jsonObject);
It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.
Dose anyone know how to fix this? Thanks in advance!
As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop

Json Array not properly generated

I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}

Categories