-1

I would like to update a different thread that I made with some code that I have written that is not working. I am trying to parse my information, which after sending a post request, looks like this [{"fromUser":"Andrew"},{"fromUser":"Jimmy"}]

I would then like to take those users, and add them to a list view. Here is my code for sending the HTTPpost and then also my code for trying to parse and put it into the adapter.

 HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(htmlUrl);

            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair("Username", "Brock"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
               HttpResponse response = httpClient.execute(httpPost);

                // writing response to log
                Log.d("Http Response:", response.toString());
            } catch (ClientProtocolException e) {
                // writing exception to log
                e.printStackTrace();
            } catch (IOException e) {
                // writing exception to log
                e.printStackTrace();
            }
            try {
                JSONObject pendingUsers = new JSONObject("$myArray");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // Read response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch(Exception e) {
                return null;
            }

            // Convert string to object
            try {
                jsonObject = new JSONObject(result);
            } catch(JSONException e) {
                return null;
            }
public void getJsonResult(JSONObject pendingRequests)
{
    pendingRequests = jsonObject;
}

Here is where I try to receive this and put it into my list

 HTTPSendPost postSender = new HTTPSendPost();
        postSender.Setup(500, 050, "tesT", htmlUrl);
        postSender.execute();

        JSONObject pendingRequests = new JSONObject();
         postSender.getJsonResult(pendingRequests);

        try {
            for(int i = 0; i < pendingRequests.length(); i++) {
                JSONArray fromUser = pendingRequests.getJSONArray("fromUser");
                pendingRequestsArray.add(i, fromUser.toString());

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_friends, pendingRequestsArray);

        pendingRequestsListView.setAdapter(adapter);

When I try it on my app, I don't get any results on the listView, any help would be appreciated. Sorry for the repost but I have a lot more information and code now. Next time I won't ask a question without the code I have tried.

PurpSchurp
  • 581
  • 5
  • 14

3 Answers3

0

In Android (i don't know if it's a Java feature) you can use JSONObject and JSONArray classes to parse, store and work with JSON

JSONObject myObject = new JSONObject(responseString);

Once your JSONObject is initialized you can fetch values from it with:

myObject.getString(key);//String, or Integer, or whatever JSON admits
Sherekan
  • 536
  • 3
  • 14
  • this is perfect, but what is the responseString, is this in the class I want to use the Object in, or is this in my class where I send the post? @Sherekan – PurpSchurp Mar 16 '15 at 16:55
  • "responseString" here is the response you fetch from your server, in this case it would be: [{"fromUser":"Andrew"},{"fromUser":"Jimmy"}] and you should use JSONArray class to store and process it, inside JSONArray class you can fetch each JSONObject with "myJSONArray.getJSONObject(int index)" method – Sherekan Mar 16 '15 at 16:56
  • So something like this JSONObject pendingUsers = new JSONObject("$myArray"); – PurpSchurp Mar 16 '15 at 17:00
  • Eww, no, "$myArray" is a plain Java String and you need a JSON formatted string, the right answer would be JSONArray pendingUsers = new JSONArray("[{"fromUser":"Andrew"},{"fromUser":"Jimmy"}]"); but for sure you can put a variable holding that string inside the constructor. Notice that quote marks aren't escaped in this example, so if you hardcode this inside your IDE it won't work – Sherekan Mar 16 '15 at 17:50
  • Sorry i dind't see it, what does the log prints in "response.toString()"? – Sherekan Mar 16 '15 at 17:52
  • new JSONArray("[{"fromUser":"Andrew"},{"fromUser":"Jimmy"}]"); this is hardcoded but how do I not hardcode that. – PurpSchurp Mar 16 '15 at 17:53
  • if inside your variable "responseString" it's "[{"fromUser":"Andrew"},{"fromUser":"Jimmy"}]" then you can: new JSONArray(responseString) – Sherekan Mar 16 '15 at 17:54
  • response.toString(); is the httpPost execute – PurpSchurp Mar 16 '15 at 17:54
  • Well i just saw your edit, i don't think you need all of this StringBuilder and BufferedReader code, just inside your HTTPResponse variable should be the JSON read from the server, and this is what you pass to the JSONArray constructor as a parameter, that's all. – Sherekan Mar 16 '15 at 17:57
  • so somehting like this HttpResponse response = httpClient.execute(httpPost); JSONObject pendingUsers = new JSONObject((response)); – PurpSchurp Mar 16 '15 at 18:00
  • Yes but you may need JSONArray instead of JSONObject. You can find more info here: http://stackoverflow.com/questions/12289844/difference-between-jsonobject-and-jsonarray and here: http://stackoverflow.com/questions/12142238/add-jsonarray-to-jsonobject. If my answer helped you please mark it as accepted so it can help other people – Sherekan Mar 16 '15 at 20:01
0

Try using JSONArray - it has a constructor that accepts a JSON String, then you can access it. For example:

myJsonString = "{\"Andrew\", \"Jimmy\"}";

JSONArray array = new JSONArray(myJsonString);

for(int i = 0; i < array.length(); i++) {
    Log.v("json", array.optString(i));

    // You can also use this
    Log.v("json", array.getString(i));

    // Or this, but you have to coerce yourself
    Log.v("json", array.get(i).toString());
}
mkorcha
  • 171
  • 1
  • 11
0

Response:

[
 {"fromUser":"Andrew"},
 {"fromUser":"Jimmy"}
]

So basically, what you are receiving is a JSON Array. I would suggest, you rather encode your data as a JSON object from the backend and receive it on the app-side as,

{ 
   "DATA":[
      {"fromUser":"Andrew", "toUser":"Kevin"},
      {"fromUser":"Jimmy", "toUser":"David"}
    ]
}

This would be your android-end code in Java.

void jsonDecode(String jsonResponse) { try { JSONObject jsonRootObject = new JSONObject(jsonResponse); JSONArray jData = jsonRootObject.getJSONArray("DATA"); for(int i = 0; i < jData.length(); ++i) { JSONObject jObj = jData.getJSONObject(i); String fromUser = jObj.optString("fromUser"); String toUser = jObj.optString("toUser"); Toast.makeText(context, "From " + fromUser "To" + toUser + ".",0).show(); } } catch(JSONException e) { e.printStackTrace(); } }

Soumojit Ghosh
  • 921
  • 7
  • 16