0

I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.

public class NewTest extends AppCompatActivity {    TextView
txtJson;
       Button btnOkay;
        @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_new_test);
            txtJson= (TextView) findViewById(R.id.txtJson);

           assert (findViewById(R.id.btnOkay)) != null;
           (findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {   new TaskPostWebService("written url here").execute(((TextView)   
findViewById(R.id.txtJson)).getText().toString());

               }
           });  }
       private class TaskPostWebService extends AsyncTask<String,Void,String> {
           private String url;
           private ProgressDialog progressDialog;
           private JSONParser jsonParser;

           public TaskPostWebService(String url ){

               this.url = url;
           }
           @Override
           protected void onPreExecute() {
               super.onPreExecute();
               progressDialog = ProgressDialog.show(NewTest.this,"","");
           }

           @Override
           protected String doInBackground(String... params) {

            String fact = "";
               try {

                   final MediaType JSON = MediaType.parse("application/json");

                   android.util.Log.e("charset", "charset - " + JSON.charset());
                   OkHttpClient client = new OkHttpClient();
       //Create a JSONObject with the data to be sent to the server
                   final JSONObject dataToSend = new JSONObject()
                           .put("nonce", "G9Ivek")
                           .put("iUserId", "477");

                   android.util.Log.e("data - ", "data - " + dataToSend.toString());
       //Create request object
                   Request request = new Request.Builder()
                           .url("written url here")
                           .post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
                           .addHeader("Content-Type", "application/json")
                           .build();

                   android.util.Log.e("request - ", "request - " + request.toString());
                   android.util.Log.e("headers - ", "headers - " + request.headers().toString());
                   android.util.Log.e("body - ", "body - " + request.body().toString());
       //Make the request
                   Response response = client.newCall(request).execute();
                   android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
                   String responseData = response.body().string();
       //Construct JSONObject of the response string
                   JSONObject dataReceived = new JSONObject(responseData);
       //See the response from the server
                   Log.i("response data", dataReceived.toString());
               }
               catch (Exception e){
                   e.printStackTrace();
               }
               return fact;
           }

           @Override
           protected void onPostExecute(String s) {
               super.onPostExecute(s);
               TextView text = (TextView) findViewById(R.id.txtJson);
               text.setText(s); 
               progressDialog.dismiss();
           }
       }

So, how can I get a response in a list and show it in a ListView?

Rujuta
  • 1
  • 6
  • add your dataReceived json object – Pavya Jul 28 '16 at 06:33
  • This depends on the JSON response format and how you want to present it in your listView. Could you describe it? – Ishita Sinha Jul 28 '16 at 06:34
  • Tons of tutorials available for that. See here, http://stackoverflow.com/questions/5490789/json-parsing-using-gson-for-java and http://www.vogella.com/tutorials/AndroidListView/article.html – K Neeraj Lal Jul 28 '16 at 06:35
  • see this tutorial it may help you https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/ – Manish Jul 28 '16 at 06:36
  • 2
    Possible duplicate of [how to display fetched json data into listview using baseadapter](http://stackoverflow.com/questions/21662673/how-to-display-fetched-json-data-into-listview-using-baseadapter) – SaravInfern Jul 28 '16 at 06:37
  • see this link you get idea how to perform web service and get response in json as well how to parse it.http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ – Vishal Thakkar Jul 28 '16 at 06:39
  • My json response is something like this {"shoppingDealsCount":"4","shoppingDeals":[{"deal_id":"13","title":"t2","category":"Entertainment","description":".....}]}],"code":"1","message":"Deals Package list data found"} so how to parse it first? I have not taken list .. – Rujuta Jul 28 '16 at 12:42

2 Answers2

2

Welcome to stackOverflow, as you are beginner so before going to complete solutions, you can think and follow following steps.

1.Network request: For network request, we have lib volley(by Google) and retrofit(by Square). You can use this for network request and response.

2.JSON Parsing: You can used eigther GSON lib or using JSONObject/ jsonArray to parse json data. I'll recommend you to write your own parsing code for better understanding of JSON parsing.

3.ListView data binding: At this step, you should have parsed data in list(other data structure can be used to store data also). Create Adapter and bind listview with adapters.

I have not provided solutions for this, you should implement yourself and let me know for any doubts. Hope this should work.

Dilip
  • 2,271
  • 5
  • 32
  • 52
0
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);

now in a separate thread:

JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
    JSONObject jsonObject = jArray.getJSONObject(i);
    arrayList.add(jsonObject.optString("INNER_KEY"));
    arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();
Geet Choubey
  • 1,069
  • 7
  • 23
  • My json response is something like this {"shoppingDealsCount":"4","shoppingDeals":[{"deal_id":"13","title":"t2","category":"Entertainment","description":".....}]}],"code":"1","message":"Deals Package list data found"} so how to parse it first? – Rujuta Jul 28 '16 at 12:41
  • `JSONObject jResponse = new JSONObject(responseStr); String dealsCount = jResponse.optString("shoppingDealsCount");` – Geet Choubey Jul 29 '16 at 06:07
  • `JSONArray deals = jResponse.optJSONArray("shoppingDeals"); ` and so ON – Geet Choubey Jul 29 '16 at 06:10
  • Thanks but still getting org.json.JSONException: Expected ':' after Response at character 10 of {Response{protocol=http/1.1, code=200, message=OK, url=http://.....}} – Rujuta Jul 29 '16 at 08:34
  • Sorry for the late response but I think you should parse your JSON response first and then try it in your code. [http://json.parser.online.fr/](http://json.parser.online.fr/) – Geet Choubey Aug 06 '16 at 17:04