package com.example.nemophila.viewmodels; import com.example.nemophila.entities.Account; import com.example.nemophila.resources.AccountsRest; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; public class AccountViewModel extends ViewModel { // フィールド private final Retrofit retrofit; private final AccountsRest accountsRest; // ライブデータ private final MutableLiveData<Account> accountLiveData; // コンストラクタ public AccountViewModel() { this.accountLiveData = new MutableLiveData<>(); this.retrofit = new Retrofit.Builder() .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/nemophila/") .addConverterFactory(JacksonConverterFactory.create()) .build(); this.accountsRest = retrofit.create(AccountsRest.class); } // ライブデータの取得 public MutableLiveData<Account> getAccountLiveData() { return accountLiveData; } // アカウント情報の取得 public void getAccount(String uid) { Call<Account> call = accountsRest.getAccount(uid); call.enqueue(new Callback<Account>() { @Override public void onResponse(Call<Account> call, Response<Account> response) { if (response.isSuccessful()) { accountLiveData.setValue(response.body()); } else { System.out.println("response error"); } } @Override public void onFailure(Call<Account> call, Throwable t) { System.out.println("correspondence error"); } }); } // アカウント名の変更 public void changeName(String uid, String name, String token) { Call<Void> call = accountsRest.changeName(uid, name, token); call.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { System.out.println("successful"); } else { System.out.println("response error"); } } @Override public void onFailure(Call<Void> call, Throwable t) { System.out.println("correspondence error"); } }); } }