Вы не можете установить любое значение TextView
из фонового процесса или задачи, например фонового сетевого вызова. Поскольку вы используете firstname.setText(first_names);
в фоновом сетевом вызове, он не будет работать. Используйте MutableLiveData
в своем ViewModel
, затем наблюдайте за ним из своего Activity
и внутри вашего наблюдателя обновите свой TextView
, например:
firstname.setText(first_names);
Когда вы получите значение из своего API, установите его на MutableLiveData
, он автоматически обновит ваш TextView.
Создайте MutableLiveData
в своем ViewModel
, например:
public class MyViewModel extends ViewModel {
// Create a LiveData with a String value
private MutableLiveData<String> firstName;
public MutableLiveData<String> getFirstName() {
if (firstName == null) {
firstName = new MutableLiveData<String>();
}
return firstName;
}
// Rest of the ViewModel below...
}
Обратите внимание на значение firstName
из Activity
и обновите TextView
с последним значением, например это:
public class YourActivity extends AppCompatActivity {
private ViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get an instance of ViewModel.
model = new ViewModelProvider(this).get(ViewModel.class);
// Create the observer which updates the UI.
final Observer<String> firstNameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newFirstName) {
// Update the TextView here with latest value
firstname.setText(newFirstName);
}
};
// Observe the MutableLiveData, passing this activity as the LifecycleOwner to the observer.
model.getCurrentName().observe(this, nameObserver);
}
}
Наконец, когда вы получите firstName
с сервера, отправьте его на MutableLiveData
с именем firstName
, чтобы обновить TextView
следующим образом:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
UserModule userModule = response.body();
String success = userModule.getSuccess();
if (success.equals("true")) {
Results_Users results = userModule.getResult();
records = results.getRecords();
for (Records records1 : records) {
String user_name = records1.getUser_name();
String id = records1.getId();
Log.d("id", id);
String first_name = records1.getFirst_name();
Log.d("first_name", first_name);
String last_name = records1.getLast_name();
String email1 = records1.getEmail1();
String title = records1.getTitle();
Records records2 = new Records(user_name, title, first_name, last_name, email1, id);
recordsList.add(records2);
ArrayList<String> records_lis=new ArrayList<>();
records_lis.add(recordsList.toString());
Log.d("records_lis", String.valueOf(records_lis.size()));
Log.d("size", String.valueOf(recordsList.size()));
for (int i = 0; i < recordsList.size(); i++)
if (username.equalsIgnoreCase(user_name)) {
String first_names = recordsList.get(0).getFirst_name();
model.getCurrentName().postValue(first_names);
}
}
}
Тогда ваш TextView
будет правильно обновлен с последним значением, полученным в результате вашего вызова API.