
929views
Hiii developer in this android solution we are discussing the Grid layout to show data the same as to the image. First of all, we get a response from the rest API with JSONArray. JSONArray parsing with grid layout. This an easy way to implement the JSON Response to Array list data to display on-screen in a grid layout.
Add Grid Layout in the XML file like these.
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/grid"
android:columnWidth="75dip"
android:gravity="left"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="75dip"/>
Java Source code with JSON Response With Volley.
// Get Request For JSONObject
public void BolgDetails(){
final ProgressDialog loading = new ProgressDialog(Blog_Details.this);
loading.setMessage("Please Wait...");
loading.setCanceledOnTouchOutside(false);
loading.show();
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, ConfiURL.Resource_FullDetail_URL+Blog_Id, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
Log.d("JSON", String.valueOf(response));
loading.dismiss();
String Error = response.getString("httpStatus");
if(Error.equals("OK")){
JSONObject Body = response.getJSONObject("body");
JSONArray teg = Body.getJSONArray("resourceTags");
Resourceteg(teg);
}else if(Error.equals("")||Error.equals(null)){
}else {
}
} catch (JSONException e) {
e.printStackTrace();
loading.dismiss();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
VolleyLog.d("Error", "Error: " + error.getMessage());
Toast.makeText(Blog_Details.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", Token);
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(req);
}
protected void Resourceteg(JSONArray response){
// initialize list
ArrayList<String> tubeLines = new ArrayList<String>();
tubeLines.equals(null);
try {
for(int i=0;i<response.length();i++) {
// Get current json object
JSONObject line = response.getJSONObject(i);
// Get the current line (json object) data
// To avoid crash use optString
String Name = line.optString("name");
tubeLines.add(Name);
}
GridView myGrid=(GridView)findViewById(R.id.grid);
myGrid.setAdapter(new ArrayAdapter<String>(this,R.layout.resource_teg, tubeLines));
} catch (JSONException e) {
Toast.makeText(Blog_Details.this, e.toString(), Toast.LENGTH_LONG).show();
}
}





