在上一篇有关使用Retrofit库在Android中进行JSON解析的文章中,我们了解了如何从android应用程序中的JSON Object获取数据并在我们的应用程序中显示该JSON Object。在本文中,我们将研究如何从JSON数组提取数据并将其显示在我们的应用程序中。
Note: To extract Data from JSON Array in Android using Volley Library please refer to How to Extract Data from JSON Array in Android using Volley Library?
JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with “[” braces opening and “]” braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair.
我们将在本文中构建什么?
我们将构建一个简单的应用程序,在其中显示CardView列表,并在其中显示一些适用于Geeks for Geeks的课程。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。
下面是我们的JSON数组,我们将通过该数组在Android App中显示数据。
[
{
"courseName":"Fork CPP",
"courseimg":"https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png",
"courseMode":"Online Batch",
"courseTracks":"6 Tracks"
},
{
"courseName":"Linux & Shell Scripting Foundation",
"courseimg":"https://media.geeksforgeeks.org/img-practice/banner/linux-shell-scripting-thumbnail.png",
"courseMode":"Online Batch",
"courseTracks":"8 Tracks"
},
{
"courseName":"11 Weeks Workshop on Data Structures and Algorithms",
"courseimg":"https://media.geeksforgeeks.org/img-practice/banner/Workshop-DSA-thumbnail.png",
"courseMode":"Online Batch",
"courseTracks":"47 Tracks"
},
{
"courseName":"Data Structures and Algorithms",
"courseimg":"https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png",
"courseMode":"Online Batch",
"courseTracks":"24 Tracks"
}
]
分步实施
步骤1:创建一个新项目
要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。
步骤2:在您的build.gradle文件中添加以下依赖项
以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。我们已将Picasso依赖项用于从URL加载图像。
// below dependancy for using retrofit.
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’
// below dependancy for using picasso image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。
步骤3:在AndroidManifest.xml文件中向Internet添加权限
导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。
XML
XML
Java
public class RecyclerData {
// string variables for our data
// make sure that the variable name
// must be similar to that of key value
// which we are getting from our json file.
private String courseName;
private String courseimg;
private String courseMode;
private String courseTracks;
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;
}
public RecyclerData(String courseName, String courseimg, String courseMode, String courseTracks) {
this.courseName = courseName;
this.courseimg = courseimg;
this.courseMode = courseMode;
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 RecyclerViewAdapter extends RecyclerView.Adapter {
// creating a variable for our array list and context.
private ArrayList courseDataArrayList;
private Context mcontext;
// creating a constructor class.
public RecyclerViewAdapter(ArrayList recyclerDataArrayList, Context mcontext) {
this.courseDataArrayList = recyclerDataArrayList;
this.mcontext = mcontext;
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// Inflate Layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
// Set the data to textview from our modal class.
RecyclerData modal = courseDataArrayList.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() {
// this method returns the size of recyclerview
return courseDataArrayList.size();
}
// View Holder Class to handle Recycler View.
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
// creating variables for our views.
private TextView courseNameTV, courseModeTV, courseTracksTV;
private ImageView courseIV;
public RecyclerViewHolder(@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 java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitAPI {
// as we are making get request so we are displaying
// GET as annotation.
// and inside we are passing last parameter for our url.
@GET("WO6S")
// as we are calling data from array so we are calling
// it with array list and naming that method as getAllCourses();
Call> getAllCourses();
}
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 java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
// creating a variable for recycler view,
// array list and adapter class.
private RecyclerView courseRV;
private ArrayList recyclerDataArrayList;
private RecyclerViewAdapter recyclerViewAdapter;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourse);
progressBar = findViewById(R.id.idPBLoading);
// creating new array list.
recyclerDataArrayList = new ArrayList<>();
// calling a method to
// get all the courses.
getAllCourses();
}
private void getAllCourses() {
// on below line we are creating a retrofit
// builder and passing our base url
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonkeeper.com/b/")
// on below line we are calling add
// Converter factory as Gson converter factory.
.addConverterFactory(GsonConverterFactory.create())
// at last we are building our retrofit builder.
.build();
// below line is to create an instance for our retrofit api class.
RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
// on below line we are calling a method to get all the courses from API.
Call> call = retrofitAPI.getAllCourses();
// on below line we are calling method to enqueue and calling
// all the data from array list.
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
// inside on response method we are checking
// if the response is success or not.
if (response.isSuccessful()) {
// on successful we are hiding our progressbar.
progressBar.setVisibility(View.GONE);
// below line is to add our data from api to our array list.
recyclerDataArrayList = response.body();
// below line we are running a loop to add data to our adapter class.
for (int i = 0; i < recyclerDataArrayList.size(); i++) {
recyclerViewAdapter = new RecyclerViewAdapter(recyclerDataArrayList, MainActivity.this);
// below line is to set layout manager for our recycler view.
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
// setting layout manager for our recycler view.
courseRV.setLayoutManager(manager);
// below line is to set adapter to our recycler view.
courseRV.setAdapter(recyclerViewAdapter);
}
}
}
@Override
public void onFailure(Call> call, Throwable t) {
// in the method of on failure we are displaying a
// toast message for fail to get data.
Toast.makeText(MainActivity.this, "Fail to get data", Toast.LENGTH_SHORT).show();
}
});
}
}
步骤4:使用activity_main.xml文件
导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。
XML格式
第5步:创建用于存储数据的模式类
导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为RecyclerData,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。
Java
public class RecyclerData {
// string variables for our data
// make sure that the variable name
// must be similar to that of key value
// which we are getting from our json file.
private String courseName;
private String courseimg;
private String courseMode;
private String courseTracks;
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;
}
public RecyclerData(String courseName, String courseimg, String courseMode, String courseTracks) {
this.courseName = courseName;
this.courseimg = courseimg;
this.courseMode = courseMode;
this.courseTracks = courseTracks;
}
}
第6步:为我们的RecyclerView的每个项目创建一个布局文件
导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件名指定为card_layout,并向其中添加以下代码。
XML格式
步骤7:创建用于将数据设置到我们的RecyclerView项的Adapter类
要创建新的Adapter类,请导航至应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将其命名为RecyclerViewAdapter并向其中添加以下代码。
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 RecyclerViewAdapter extends RecyclerView.Adapter {
// creating a variable for our array list and context.
private ArrayList courseDataArrayList;
private Context mcontext;
// creating a constructor class.
public RecyclerViewAdapter(ArrayList recyclerDataArrayList, Context mcontext) {
this.courseDataArrayList = recyclerDataArrayList;
this.mcontext = mcontext;
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// Inflate Layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
// Set the data to textview from our modal class.
RecyclerData modal = courseDataArrayList.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() {
// this method returns the size of recyclerview
return courseDataArrayList.size();
}
// View Holder Class to handle Recycler View.
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
// creating variables for our views.
private TextView courseNameTV, courseModeTV, courseTracksTV;
private ImageView courseIV;
public RecyclerViewHolder(@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:创建用于编写我们的API调用的接口类
导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,将其选择为Interface并将文件命名为RetrofitAPI并向其添加以下代码。在代码内部添加了注释,以更详细地了解代码。
Java
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitAPI {
// as we are making get request so we are displaying
// GET as annotation.
// and inside we are passing last parameter for our url.
@GET("WO6S")
// as we are calling data from array so we are calling
// it with array list and naming that method as getAllCourses();
Call> getAllCourses();
}
步骤9:使用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 java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
// creating a variable for recycler view,
// array list and adapter class.
private RecyclerView courseRV;
private ArrayList recyclerDataArrayList;
private RecyclerViewAdapter recyclerViewAdapter;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourse);
progressBar = findViewById(R.id.idPBLoading);
// creating new array list.
recyclerDataArrayList = new ArrayList<>();
// calling a method to
// get all the courses.
getAllCourses();
}
private void getAllCourses() {
// on below line we are creating a retrofit
// builder and passing our base url
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonkeeper.com/b/")
// on below line we are calling add
// Converter factory as Gson converter factory.
.addConverterFactory(GsonConverterFactory.create())
// at last we are building our retrofit builder.
.build();
// below line is to create an instance for our retrofit api class.
RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
// on below line we are calling a method to get all the courses from API.
Call> call = retrofitAPI.getAllCourses();
// on below line we are calling method to enqueue and calling
// all the data from array list.
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
// inside on response method we are checking
// if the response is success or not.
if (response.isSuccessful()) {
// on successful we are hiding our progressbar.
progressBar.setVisibility(View.GONE);
// below line is to add our data from api to our array list.
recyclerDataArrayList = response.body();
// below line we are running a loop to add data to our adapter class.
for (int i = 0; i < recyclerDataArrayList.size(); i++) {
recyclerViewAdapter = new RecyclerViewAdapter(recyclerDataArrayList, MainActivity.this);
// below line is to set layout manager for our recycler view.
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
// setting layout manager for our recycler view.
courseRV.setLayoutManager(manager);
// below line is to set adapter to our recycler view.
courseRV.setAdapter(recyclerViewAdapter);
}
}
}
@Override
public void onFailure(Call> call, Throwable t) {
// in the method of on failure we are displaying a
// toast message for fail to get data.
Toast.makeText(MainActivity.this, "Fail to get data", Toast.LENGTH_SHORT).show();
}
});
}
}
现在运行您的应用程序,并查看该应用程序的输出。