Ví dụ này trình bày cách phân tích cú pháp các Đối tượng JSON trên Android.
Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.
Bước 2 - Thêm phần phụ thuộc sau vào Gradle Scripts ⇒ build.gradle và thực hiện đồng bộ hóa
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.sample"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView
implementation 'com.android.support:cardview-v7:23.0.1' // dependency file for CardView
} Bước 3 - Thêm phần phụ thuộc sau vào res / layout / activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
Bước 4 - Thêm phần phụ thuộc sau vào res / layout / rowlayout _main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/cardView" android:layout_width="match_parent" android:layout_margin="5dp" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <!--items for a single row of RecyclerView--> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/tvEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="email@email.com" android:textColor="#000" android:textSize="15sp" /> <TextView android:id="@+id/tvMobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="e9999999999" android:textColor="#000" android:textSize="15sp" /> </LinearLayout> </android.support.v7.widget.CardView>
Bước 5 - Thêm phần phụ thuộc sau vào src / MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
// ArrayList for person names, email Id's and mobile numbers
ArrayList<String> personNames=new ArrayList<>();
ArrayList<String> emailIds=new ArrayList<>();
ArrayList<String> mobileNumbers=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of RecyclerView
RecyclerView recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
// set a LinearLayoutManager with default vertical orientation
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
try {
// get JSONObject from JSON file
JSONObject obj=new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray=obj.getJSONArray("users");
// implement for loop for getting users list data
for (int i = 0; i < userArray.length(); i++) {
// create a JSONObject for fetching single user data
JSONObject userDetail=userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
personNames.add(userDetail.getString("name"));
emailIds.add(userDetail.getString("email"));
// create a object for getting contact data from JSONObject
JSONObject contact=userDetail.getJSONObject("contact");
// fetch mobile number and store it in arraylist
mobileNumbers.add(contact.getString("mobile"));
}
} catch (JSONException e) {
e.printStackTrace();
}
// call the constructor of CustomAdapter to send the reference and data to Adapter
CustomAdapter customAdapter=new CustomAdapter(MainActivity.this, personNames, emailIds, mobileNumbers);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
}
public String loadJSONFromAsset() {
String json=null;
try {
InputStream is=getAssets().open("users_list.json");
int size=is.available();
byte[] buffer=new byte[size];
is.read(buffer);
is.close();
json=new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
} Bước 6 - Thêm phần phụ thuộc sau vào src / CustomAdapter.java
package com.example.sample;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> personNames;
ArrayList<String> emailIds;
ArrayList<String> mobileNumbers;
Context context;
public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> emailIds, ArrayList<String> mobileNumbers) {
this.context=context;
this.personNames=personNames;
this.emailIds=emailIds;
this.mobileNumbers=mobileNumbers;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
MyViewHolder vh=new MyViewHolder(v); // pass the view to View Holder
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
holder.name.setText(personNames.get(position));
holder.email.setText(emailIds.get(position));
holder.mobileNo.setText(mobileNumbers.get(position));
// implement setOnClickListener event on item view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// display a toast with person name on item click
Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return personNames.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, email, mobileNo; // init the item view's
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name=(TextView) itemView.findViewById(R.id.tvName);
email=(TextView) itemView.findViewById(R.id.tvEmail);
mobileNo=(TextView) itemView.findViewById(R.id.tvMobile);
}
}
} Bước 7 - Thêm mã sau vào ứng dụng / tệp kê khai / AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn -