-2

I have the following JSON response:

{  
   "success":1,
   "message":"Post Available!",
   "posts":[  
      {  
         "id":"1",
         "name":"hi",
         "phone":"123",
         "department":"and",
         "days":"1",
         "reason":"SICK"
      },
      {  
         "id":"2",
         "name":"at",
         "phone":"0000000",
         "department":"android",
         "days":"60",
         "reason":"sick"
      },
      {  
         "id":"3",
         "name":"as",
         "phone":"21",
         "department":"as",
         "days":"3",
         "reason":"git"
      },
      {  
         "id":"4",
         "name":"abcd",
         "phone":"123",
         "department":"abcd",
         "days":"1",
         "reason":"abcd"
      }
   ]
}

How can I implement this on list view? My JSONParser class as:

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {    
}    

public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;    
}    

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

And my Main activity code (activity_main) contains only a listview (extends ListActivity). Do I have to add any layout file, or do I have to change the JSONparse class?

Thanks in advance.

agold
  • 6,140
  • 9
  • 38
  • 54

3 Answers3

1

Yes Atif, You have to use custom adapter to show data in ListView. You have to create your own layout for listview & it will inflate in your custom adapter. You can refer below link for this: Listview Adapter

Kuldeep Kulkarni
  • 796
  • 5
  • 20
1

First of all Add following lines to build.gradle (Module:app)

 compile 'com.google.code.gson:gson:2.2.4'

After that create a layout of what u want to show in ListView:I have jsut shown name, phone from your json:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:orientation="vertical">


    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</LinearLayout>

Then create an adapter class:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;



public class ListViewAdapter extends BaseAdapter {
    private final JsonResponseDTO data;
    private final Context ctx;
    private final LayoutInflater inflater;
    View v;

    public ListViewAdapter(Context ctx, JsonResponseDTO response) {
        this.data = response;
        this.ctx = ctx;
        inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        if (data.posts.size() > 0) {
            return data.posts.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return data.posts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        v = convertView;
        UserDetDTO dto = data.posts.get(position);
        ViewHolder vh = new ViewHolder();
        if (convertView == null) {
            v = inflater.inflate(R.layout.row, null);
        }
        vh.tvName = (TextView) v.findViewById(R.id.name);
        vh.tvPhone = (TextView) v.findViewById(R.id.phone);

        vh.tvName.setText(dto.name);
        vh.tvPhone.setText(dto.phone);

        return v;
    }

    private static class ViewHolder {
        public TextView tvName, tvPhone;
    }
}

After that call this from Activity class and set adapter in Listview like:

public class ListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        ListView lv = (ListView) findViewById(R.id.lv);

        JSONObject json = /* JSON u recieved from server*/;

        JsonResponseDTO jsonRes = new GsonBuilder().create().fromJson(json.toString(), JsonResponseDTO.class);
        if (jsonRes != null) {
            ListViewAdapter adapter = new ListViewAdapter(ListActivity.this, jsonRes);
            lv.setAdapter(adapter);
        }

    }
}
asad.qazi
  • 2,449
  • 3
  • 23
  • 35
  • This code is from you json response. I just showed name and phone number – asad.qazi Dec 29 '15 at 12:14
  • hey Thanks but its not what I want ... I wanna get that from URL ..... Also that GSON library is not compiling – Atif Patel Dec 30 '15 at 04:36
  • According to your question you said that " I have the following JSON response:" So you just need the listview implementation which I already implemented for you. – asad.qazi Dec 30 '15 at 05:58
0

This may help you:

1) Create a model class with getters and setters for storing the JSON data.

2) Parse JSON and store in an ArrayList<>. // You can use Gson for parsing.

3) Create a layout.xml for displaying list items.

5) Create an adapter class extending BaseAdapter and set the data using layout.xml.

4) Populate data in the list.

Faraz
  • 2,144
  • 1
  • 18
  • 28