android - 如何解析json数据并在 GridView 中显示

标签 android json gridview

我正在从事一个项目,因为我想在 GridView 中显示 JSON 数据。我尝试截击来获取数据,但数据未显示在 GridView 中。下面是我的 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": ""
    }
]

下面的代码是我的主要 Activity

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

最佳答案

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);
}

关于android - 如何解析json数据并在 GridView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100941/

相关文章:

android - 如何在 android 中定义乌尔都语 (Jameel Noori Nastaleeq) 字体的空格?

c# - 网络共享/SMB 客户端

Android视频帧处理

javascript - 获取托管在 github 上的 json 列表 - 不推送到 html

javascript - 如何将 AJAX 字符串响应转换为 JSON

android - 如何以编程方式向 GridView 添加空行 :

c# - 使用 AutoGenerateColumns 将超链接绑定(bind)到 GridView

android sqlite 约束更新失败

sql - postgresql 在 where 子句中使用 json 子元素

android - 在 Android 的 GridView 中记录 2 列随机播放?