-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.

5
  • what you have tried ? Commented Mar 16, 2015 at 16:43
  • I have tried to use a Parse JSON class(Which I have now deleted because it was not working), but that doesn't work for me because I really need to send the post with parameters and the parse class I created couldn't do that. (Not sure how to do that. I'm not that advanced) Commented Mar 16, 2015 at 16:44
  • will you share the code what you have done Commented Mar 16, 2015 at 16:46
  • Hmm, I wish I could but I deleted it, Let me try to write up some new code @Fahim Commented Mar 16, 2015 at 16:47
  • @Fahim I have updated my code completely Commented Mar 16, 2015 at 17:50

3 Answers 3

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());
}
Sign up to request clarification or add additional context in comments.

Comments

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

11 Comments

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
"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
So something like this JSONObject pendingUsers = new JSONObject("$myArray");
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
Sorry i dind't see it, what does the log prints in "response.toString()"?
|
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(); } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.