Android 在片段内观察到的LiveData始终为空

Android 在片段内观察到的LiveData始终为空,android,android-fragments,mvvm,android-viewmodel,Android,Android Fragments,Mvvm,Android Viewmodel,我试图从RestAPI获取数据,用MVVM显示BottomNavigationView的内部片段。 我使用DataRepository(改装)和ViewModel从REstAPI作为逻辑层获取数据 当我签入logcat时,数据成功地从RestAPI获取到DataRepository,但当我签入视图(片段)时,它总是返回NULL 重新启动PI响应: { "responseCode": "00", "responseDescription": "OK", "responseD

我试图从RestAPI获取数据,用MVVM显示BottomNavigationView的内部片段。 我使用DataRepository(改装)和ViewModel从REstAPI作为逻辑层获取数据

当我签入logcat时,数据成功地从RestAPI获取到DataRepository,但当我签入视图(片段)时,它总是返回NULL

重新启动PI响应

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
请求.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
ApiRequest.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
活动\u main.xml

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}

BerandaRepository.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
公共类存储库{
私有静态最终字符串标记=BerandaRepository.class.getSimpleName();
私人ApiRequest-ApiRequest;
公共存储库(){
APIRESQUEST=REFORMATREQUEST.getClient().create(APIRESQUEST.class);
}
公共LiveData GetDataBernda(JsonObject参数){
最终的MutableLiveData数据=新的MutableLiveData();
APIRESQUEST.beranda(参数)
.enqueue(新的回调函数(){
@凌驾
公共void onResponse(调用、响应){
Log.d(标记“onResponse::”+response);
if(response.body()!=null){
ApiResponse ApiResponse=新的ApiResponse(响应);
if(apiResponse.issucess()){
setValue(apiResponse.getDataJsonObject());
}否则{
data.setValue(空);
}
}否则{
data.setValue(空);
d(标记“else-onResponse::null”);
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
data.setValue(空);
}
});
返回数据;
}
}
BerandaViewModel.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
公共类BerandaViewModel扩展了AndroidViewModel{
私人贝兰达存储库贝兰达存储库;
私有LiveData JSONObject LiveData;
公共BerandaViewModel(@NonNull应用程序){
超级(应用);
this.berandaRepository=新的berandaRepository();
this.jsonObjectLiveData=this.berandaRepository.getdataberada(新的JsonObject());
}
公共LiveData getBerandaData(){
返回jsonObjectLiveData;
}
}
BerandaFragment.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
公共类BerandaFragment扩展了片段{
私有BerandaViewModel BerandaViewModel;
私人碎片和绑定;
私有列表URL=new ArrayList();
创建视图时的公共视图(@NonNull LayoutInflater inflater、ViewGroup容器、Bundle savedInstanceState){
绑定=数据绑定直到充气(充气器,右布局,碎片,容器,假);
初始化();
loadDataBerada();
返回binding.getRoot();
}
私有void初始化(){
berandaViewModel=ViewModelProviders.of(getActivity()).get(berandaViewModel.class);
}
私有void loadDataBernda(){
berandaViewModel.getBerandaData().observe(BerandaFragment.this,new Observer()){
@凌驾
更改后的公共无效(JsonObject JsonObject){
if(jsonObject!=null){
Log.d(“检查”,“响应:+jsonObject.toString());
JsonArray arruls=jsonObject.get(“编辑器选择”).getAsJsonArray();
用于(JsonElement je:arrURL){
JsonObject jo=je.getAsJsonObject();
add(jo.get(“image_url”).getAsString());
}
Glide.with(getContext()).load(url.get(0)).into(binding.imageView);
}否则{
Log.d(“检查”,“数据为空”);
}
}
});
}
}
ApiResponse.java

{
    "responseCode": "00",
    "responseDescription": "OK",
    "responseData": {
        "editorsChoices": [
            {
                "image_url": "https://images.pexels.com/photos/218983/pexels-photo-218983.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
            },
            {
                "image_url": "https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
            }
        ],
        "trendingProjects": [],
        "trendingWaqfs": [],
        "trendingDonations": [],
    }
}
public class RetrofitRequest {
    private static final String BASE_URL = BuildConfig.API_URL;
    private static Retrofit retrofit = null;

    private static OkHttpClient buildClient()
    {
        // start logging type
        HttpLoggingInterceptor logHeader = new HttpLoggingInterceptor();
        logHeader.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        HttpLoggingInterceptor logBody = new HttpLoggingInterceptor();
        logBody.setLevel(HttpLoggingInterceptor.Level.BODY);

        HttpLoggingInterceptor logBasic = new HttpLoggingInterceptor();
        logBasic.setLevel(HttpLoggingInterceptor.Level.BASIC);
        // end logging type

        // create client
        return new OkHttpClient.Builder()
                //.addInterceptor(logBasic)
                //.addInterceptor(logHeader)
                .addInterceptor(logBody)
                .build();
    }

    public static Retrofit getClient()
    {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(buildClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
        }
        return retrofit;
    }

    public static String getError(int errorCode){
        switch (errorCode) {
            case 400:
                return "400: Bad Request";
            case 401:
                return "401: Unauthorized";
            case 402:
                return "402: Payment Required";
            case 403:
                return "403: Forbidden";
            case 404:
                return "404: Not Found";
            case 405:
                return "405: Method Not Allowed";
            case 500:
                return "500: Internal Server Error";

        }
        return "Undefined Error";
    }
}
public interface ApiRequest {
    @POST("beranda")
    Call<JsonObject> beranda(@Body JsonObject param);
}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);

        NavController navController = Navigation.findNavController(this, R.id.bottom_nav_host_fragment);

        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

}
<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:labelVisibilityMode="labeled"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/bottom_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class BerandaRepository {
    private static final String TAG = BerandaRepository.class.getSimpleName();
    private ApiRequest apiRequest;

    public BerandaRepository() {
        apiRequest = RetrofitRequest.getClient().create(ApiRequest.class);
    }

    public LiveData<JsonObject> getDataBeranda(JsonObject params){
        final MutableLiveData<JsonObject> data = new MutableLiveData<>();
        apiRequest.beranda(params)
                .enqueue(new Callback<JsonObject>() {

                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Log.d(TAG, "onResponse response:: " + response);
                        if (response.body() != null) {
                            ApiResponse apiResponse = new ApiResponse(response);
                            if (apiResponse.isSuccess()) {
                                data.setValue(apiResponse.getDataJsonObject());
                            } else {
                                data.setValue(null);
                            }
                        } else {
                            data.setValue(null);
                            Log.d(TAG, "else onResponse response:: null" );
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        data.setValue(null);
                    }
                });
        return data;
    }
}
public class BerandaViewModel extends AndroidViewModel {
    private BerandaRepository berandaRepository;
    private LiveData<JsonObject> jsonObjectLiveData;


    public BerandaViewModel(@NonNull Application application) {
        super(application);
        this.berandaRepository = new BerandaRepository();
        this.jsonObjectLiveData = this.berandaRepository.getDataBeranda(new JsonObject());

    }

    public LiveData<JsonObject> getBerandaData(){
        return jsonObjectLiveData;
    }

}
public class BerandaFragment extends Fragment {

    private BerandaViewModel berandaViewModel;
    private FragmentBerandaBinding binding;

    private List<String> urls = new ArrayList<>();



    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_beranda, container, false);

        initialize();

        loadDataBeranda();

        return binding.getRoot();
    }

    private void initialize(){
        berandaViewModel =ViewModelProviders.of(getActivity()).get(BerandaViewModel.class);
    }

    private void loadDataBeranda(){

        berandaViewModel.getBerandaData().observe(BerandaFragment.this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    Log.d("CHECK", "response: " + jsonObject.toString());
                    JsonArray arrUrls = jsonObject.get("editorsChoices").getAsJsonArray();
                    for (JsonElement je: arrUrls) {
                        JsonObject jo = je.getAsJsonObject();
                        urls.add(jo.get("image_url").getAsString());
                    }
                    Glide.with(getContext()).load(urls.get(0)).into(binding.imageView);
                } else {
                    Log.d("CHECK", "Data is NULL");
                }
            }
        });
    }
}
public class ApiResponse {
    JsonObject body;

    public ApiResponse(Response<JsonObject> response) {
        this.body = response.body();
        Log.d("CEK", "Body: " + body.toString());
    }

    public String getCode() {
        return body.get("responseCode").getAsString();
    }

    public String getDescription(){
        return body.get("responseDescription").getAsString();
    }

    public boolean isSuccess(){
        return getCode().equals("00");
    }

    public JsonArray getDataJsonArray(){
        return body.get("responseData").getAsJsonArray();
    }

    public JsonObject getDataJsonObject(){
        return body.get("responseData").getAsJsonObject();
    }
}
公共类响应{
JsonObject体;
公众回应(回应){
this.body=response.body();
Log.d(“CEK”,“Body:+Body.toString());
}
公共字符串getCode(){
返回body.get(“responseCode”).getAsString();
}
公共字符串getDescription(){
返回body.get(“responseDescription”).getAsString();
}
公共布尔值isSuccess(){
返回getCode()。等于(“00”);
}
公共JsonArray getDataJsonArray(){
返回body.get(“responseData”).getAsJsonArray();
}
公共JsonObject getDataJsonObject(){
返回body.get(“responseData”).getAsJsonObject();
}
}

如何解决这个问题?

什么日志是按您所说的那样打印您想要的数据?从HttpLoggingInterceptor级别的正文中,我可以看到通过改装RestAPI成功地获取数据。bu当我检查BerandaFragment LoadDataBerada方法内部时,它总是执行else语句我想通过Glide从url到图像视图显示图像,当url是RestAPI=>response.responseData.EditorChoices[0]中的数据时,url尝试将apiResponse.getDataJsonObject()打印为日志中的字符串,并显示json是否有效OOH,这就是问题所在,RestAPI的响应不是正确的JsonObject,在“Trending捐款”之后有,(昏迷):[],所以我去掉了它,它就工作了