📌  相关文章
📜  如何使用Volley Library从Android的JSON数组中提取数据?

📅  最后修改于: 2021-05-09 18:10:43             🧑  作者: Mango

在上一篇有关使用Volley Library在Android中进行JSON解析的文章中,我们了解了如何从android应用程序中的JSON Object获取数据并在我们的应用程序中显示该JSON Object。在本文中,我们将研究如何从JSON数组提取数据并将其显示在我们的应用程序中。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中显示CardView列表,并在其中显示一些适用于Geeks for Geeks的课程。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

下面是我们的JSON数组,我们将通过该数组在Android App中显示数据。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。我们已将Picasso依赖项用于从URL加载图像。

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML


XML


  
    
    
  
    
    
      


Java
public class CourseModal {
  
    // variables for our course 
    // name and description.
    private String courseName;
    private String courseimg;
    private String courseMode;
    private String courseTracks;
  
    // creating constructor for our variables.
    public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) {
        this.courseName = courseName;
        this.courseimg = courseimg;
        this.courseMode = courseMode;
        this.courseTracks = courseTracks;
    }
  
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseimg() {
        return courseimg;
    }
  
    public void setCourseimg(String courseimg) {
        this.courseimg = courseimg;
    }
  
    public String getCourseMode() {
        return courseMode;
    }
  
    public void setCourseMode(String courseMode) {
        this.courseMode = courseMode;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
}


XML


  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
          
    
      


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter {
      
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseTracksTV.setText(modal.getCourseTracks());
        holder.courseModeTV.setText(modal.getCourseMode());
        Picasso.get().load(modal.getCourseimg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private TextView courseNameTV, courseModeTV, courseTracksTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseModeTV = itemView.findViewById(R.id.idTVBatch);
            courseTracksTV = itemView.findViewById(R.id.idTVTracks);
            courseIV = itemView.findViewById(R.id.idIVCourse);
        }
    }
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
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;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for 
    // our ui components.
    private RecyclerView courseRV;
      
    // variable for our adapter 
    // class and array list
    private CourseAdapter adapter;
    private ArrayList courseModalArrayList;
     
    // below line is the variable for url from
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/WO6S";
    private ProgressBar progressBar;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        progressBar = findViewById(R.id.idPB);
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
        getData();
          
        // calling method to 
        // build recycler view.
        buildRecyclerView();
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array 
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
                progressBar.setVisibility(View.GONE);
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and 
                    // getting each object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                          
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks));
                        buildRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
  
    private void buildRecyclerView() {
  
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
         
        // adding layout manager 
        // to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager 
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to 
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    
      

第5步:创建用于存储数据的Modal类

为了存储我们的数据,我们必须创建一个新的Java类。要创建新的Java类,请导航至应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseModal ,并向其添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Java

public class CourseModal {
  
    // variables for our course 
    // name and description.
    private String courseName;
    private String courseimg;
    private String courseMode;
    private String courseTracks;
  
    // creating constructor for our variables.
    public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) {
        this.courseName = courseName;
        this.courseimg = courseimg;
        this.courseMode = courseMode;
        this.courseTracks = courseTracks;
    }
  
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseimg() {
        return courseimg;
    }
  
    public void setCourseimg(String courseimg) {
        this.courseimg = courseimg;
    }
  
    public String getCourseMode() {
        return courseMode;
    }
  
    public void setCourseMode(String courseMode) {
        this.courseMode = courseMode;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
}

第6步:为我们的RecyclerView的每个项目创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件名命名为course_rv_item ,并将以下代码添加到其中。在代码中添加了注释,以便更详细地了解。

XML格式



  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
          
    
      

步骤7:创建用于将数据设置到我们的RecyclerView项的Adapter类

要创建新的适配器类,请导航至应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将其命名为CourseAdapter并向其中添加以下代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter {
      
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseTracksTV.setText(modal.getCourseTracks());
        holder.courseModeTV.setText(modal.getCourseMode());
        Picasso.get().load(modal.getCourseimg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private TextView courseNameTV, courseModeTV, courseTracksTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseModeTV = itemView.findViewById(R.id.idTVBatch);
            courseTracksTV = itemView.findViewById(R.id.idTVTracks);
            courseIV = itemView.findViewById(R.id.idIVCourse);
        }
    }
}

步骤8:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
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;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for 
    // our ui components.
    private RecyclerView courseRV;
      
    // variable for our adapter 
    // class and array list
    private CourseAdapter adapter;
    private ArrayList courseModalArrayList;
     
    // below line is the variable for url from
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/WO6S";
    private ProgressBar progressBar;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        progressBar = findViewById(R.id.idPB);
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
        getData();
          
        // calling method to 
        // build recycler view.
        buildRecyclerView();
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array 
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
                progressBar.setVisibility(View.GONE);
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and 
                    // getting each object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                          
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks));
                        buildRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
  
    private void buildRecyclerView() {
  
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
         
        // adding layout manager 
        // to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager 
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to 
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!