JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays.Source
1.Create a new android studio project
2.Create a raw directory in Res folder
3.Create a json file named cars.json and paste the following data:
[{
"make": "Noah",
"model": "Toyota"
},{
"make": "Rumion",
"model": "Toyota"
},{
"make": "Q6",
"model": "Audi"
},{
"make": "Corrola cross",
"model": "Toyota"
},{
"make": "Axela",
"model": "Mazda"
},{
"make": "Atenza",
"model": "Mazda"
},{
"make": "Wingroad",
"model": "Nissan"
},{
"make": "Spade",
"model": "Nissan"
},{
"make": "Levante",
"model": "Maserati"
},{
"make": "D-Max",
"model": "Isuzu"
},{
"make": "X-Trail",
"model": "Nissan"
},{
"make": "GTR",
"model": "Nissan"
}, {
"make": "Legacy",
"model": "Subaru"
}]
We will use CardView and RecyclerView in our code so add the dependancy in app-level build.gradle (Module:app)
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'com.android.support:cardview-v7:29.0.0'
4.Create a list_item.xml in Layout for RecyclerView and paste in the following code:
Add RecyclerView in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
tools:listitem="@layout/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Create a java file called cars.java to act as a model
public class cars {
private String model;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
private String make;
}
Create another java file RecyclerAdapter.java for displaying items.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE = 1;
private final Context context;
private final List<Object> listRecyclerItem;
public RecyclerAdapter(Context context, List<Object> listRecyclerItem) {
this.context = context;
this.listRecyclerItem = listRecyclerItem;
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView tvModel;
private TextView tvMake;
public ItemViewHolder(@NonNull View itemView) {
super(itemView);
tvModel = (TextView) itemView.findViewById(R.id.tvModel);
tvMake = (TextView) itemView.findViewById(R.id.tvMake);
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
switch (i) {
case TYPE:
default:
View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.list_item, viewGroup, false);
return new ItemViewHolder((layoutView));
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
int viewType = getItemViewType(i);
switch (viewType) {
case TYPE:
default:
ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder;
cars Cars = (cars) listRecyclerItem.get(i);
itemViewHolder.tvMake.setText(Cars.getMake());
itemViewHolder.tvModel.setText(Cars.getModel());
}
}
@Override
public int getItemCount() {
return listRecyclerItem.size();
}
}
Add the following activity in your MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private List<Object> viewItems = new ArrayList<>();
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this, viewItems);
mRecyclerView.setAdapter(mAdapter);
addItemsFromJSON();
}
private void addItemsFromJSON() {
try {
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject itemObj = jsonArray.getJSONObject(i);
String model = itemObj.getString("model");
String make = itemObj.getString("make");
cars Cars = new cars(model, make);
viewItems.add(Cars);
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: ", e);
}
}
private String readJSONDataFromFile() throws IOException{
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonString = null;
inputStream = getResources().openRawResource(R.raw.cars);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonString = bufferedReader.readLine()) != null) {
builder.append(jsonString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
Run your code,it should be displaying items as shown below:
Thats all for any questions or comments please leave in the form below:
Source code at https://github.com/Ongoma/AndroidJsonRecyclerView