如何解析json数据并在网格视图中显示

时间:2018-06-29 11:41:19

标签: android json gridview

我正在开发一个项目,因为我想在网格视图中显示JSON数据。我尝试了齐射来获取数据,但数据未显示在网格视图中。以下是我的Json API

{
"status": 200,
"msg": "success",
"data": [
    {
        "category_name": "ELECTRONICS",
        "category_description": "ELECTRONICS Items",
        "category_image": "images/uploads/a8cee9e723f669813b999ee6bfe611f42018-05-1712-36-17.jpg"
    },
    {
        "category_name": "Sports",
        "category_description": "Sports Accesories",
        "category_image": "images/uploads/76f2c9778df71ae83d04bc0d6178042f2018-05-1712-36-17.jpg"
    },
    {
        "category_name": "Dress",
        "category_description": "All Kind of dress",
        "category_image": "images/uploads/05a5efb96308db381116e90478fce2272018-05-1712-36-17.jpg"
    },
    {
        "category_name": "Cars",
        "category_description": "Automobiles",
        "category_image": ""
    }
]

}

下面的代码是我的主要活动

package shop.shop;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import shop.Fragment.AboutUsFragment;

public class Drawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
//Web api url
public static final String DATA_URL = "http://www.foliagetechnologies.com/rent/api/v1/master/category.php";

//Tag values to read from json
public static final String TAG_IMAGE_URL = "category_image";
public static final String TAG_NAME = "category_name";

//GridView Object
private GridView gridView;


//ArrayList for Storing image urls and titles
private ArrayList<String> category_image;
private ArrayList<String> category_name;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);



    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    gridView = (GridView) findViewById(R.id.grid_view_image_text);

    category_image = new ArrayList<>();
    category_name = new ArrayList<>();

    //Calling the getData method
    getData();

}

// create a method getData() to get the JSON Array from the API.
private void getData()
{
    //Showing a progress dialog while our app fetches the data from url

    final ProgressDialog loading = ProgressDialog.show(this,"Loading","Be Patience",false,false);

    //Creating a json array request to get the json from our api

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            //Dismissing the progressdialog on response

           loading.dismiss();

            //Displaying our grid
            showGrid(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                   loading.dismiss();
                    Toast.makeText(getApplicationContext(),error.getMessage()+",hello everybody",Toast.LENGTH_LONG).show();
                }
            }
    );

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding our request to the queue
    requestQueue.add(jsonArrayRequest);

}

private void showGrid(JSONArray response) {

    //Looping through all the elements of json array
    for (int i = 0; i<response.length(); i++){

        //Creating a json object of the current index

        JSONObject obj = null;

        //getting json object from current index

        try {
            obj = response.getJSONObject(i);


            //getting image url and title from json object

            category_image.add(obj.getString(TAG_IMAGE_URL));
            category_name.add(obj.getString(TAG_NAME));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //Creating GridHomeAdapter Object
    GridHomeAdapter gridhomeAdapter = new GridHomeAdapter(this,category_image,category_name);

    //Adding adapter to gridview
    gridView.setAdapter(gridhomeAdapter);
}

下面是布局文件。我没有为我的项目使用操作栏,因此我仅为操作栏创建了一个xml文件,并将其包含在此xml文件中。

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        android:id="@+id/include"
        layout="@layout/app_bar_drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_drawer"
        app:menu="@menu/activity_drawer_drawer"
        />



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="none"
        >
    <GridView
            android:id="@+id/grid_view_image_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="55dp"
            android:columnWidth="110dp"
            android:gravity="center"
            android:horizontalSpacing="10dp"
            android:verticalSpacing="10dp"
            android:numColumns="auto_fit" />
    </LinearLayout>

错误是 This the Exception I am getting..Image URL is given below

3 个答案:

答案 0 :(得分:2)

我希望这对您有用。

像这样解析json

try {
            JSONObject jsonObject=new JSONObject(reponse.toString());
            String status=jsonObject.getString("status");
            String msg=jsonObject.getString("msg");
            Log.e("status",status);
            Log.e("msg",msg);
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            for (int i = 0; i <jsonArray.length() ; i++) {

                JSONObject jsonObject1=jsonArray.getJSONObject(i);
                String category_name=jsonObject1.getString("category_name");
                String category_description=jsonObject1.getString("category_description");
                String category_image=jsonObject1.getString("category_image");

                Log.e("category_name",category_name);
                Log.e("category_description",category_description);
                Log.e("category_image",category_image);

            }

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

并使用volly StringRequest。

答案 1 :(得分:1)

在下面替换getData方法

private void getData()
{
    //Showing a progress dialog while our app fetches the data from url
    final ProgressDialog loading = ProgressDialog.show(this,"Loading","Be Patience",false,false);
    //Creating a json array request to get the json from our api
           JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, DATA_URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //Dismissing the progressdialog on response
            loading.dismiss();
            //Displaying our grid
            showGrid(response.optJSONArray("data"));            }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            loading.dismiss();
            Toast.makeText(getApplicationContext(),error.getMessage()+",hello everybody",Toast.LENGTH_LONG).show();
        }
    });
    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding our request to the queue
    requestQueue.add(jsonObjectRequest);
}

答案 2 :(得分:0)

使用JsonObjectRequest代替JsonArrayRequest

然后将showGrid(response);替换为showGrid(response.optJSONArray("data"));

相关问题