Отображается первое имя пользователя, оставшееся имя пусто в android - PullRequest
1 голос
/ 07 мая 2020

Привет, как показано ниже, у меня есть два действия: вход в систему и основной. После успешного входа в систему с правильным именем пользователя и паролем он перейдет в режим mainactivity при переходе от входа к основному действию. Я использую намерение передать имя пользователя в mainactivity.

В основном действии я вызываю APi. Из Api я получение ответа После успешного ответа я могу получить разные строки. Из этого я получаю имя, имя пользователя. Теперь из имени пользователя loginActivity и имени пользователя mainactivity. Если оба имени равны, я беру первое имя для этого пользователя и устанавливаю это в textview.

может ли кто-нибудь помочь мне, где я допустил ошибку.

Для начального пользователя я могу видеть первое имя, а затем, если я войду с другим именем пользователя, это время будет пусто

MainActivity. java:

username = getIntent().getStringExtra("username");
private void fetchUserJSON(){

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

             sessionId = getIntent().getStringExtra("sessionId");
            //username = getIntent().getStringExtra("username");
            String operation = "query";
            String query = "select  *  from Users";
            final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
            /** Call the method with parameter in the interface to get the notice data*/
            Call<UserModule> call = service.UserRecordDetails(operation, sessionId, query);
            /**Log the URL called*/
            Log.i("URL Called", call.request().url() + "");
            call.enqueue(new Callback<UserModule>() {
                @Override
                public void onResponse(Call<UserModule> call, Response<UserModule> response) {
                    Log.e("response", new Gson().toJson(response.body()));
                    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();
                                        firstname.setText(first_names);
                                    }
                            }
                        }
                    }
                }
                @Override
                public void onFailure(Call<UserModule> call, Throwable t) {
                }
                //     progressDialog.dismiss();
            });
        }
    }, 0);
    return ;
}

Класс модели:

public class Records {

    @SerializedName("user_name")
    @Expose
    private String user_name;
    @SerializedName("title")
    @Expose
    private String title;


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }


    public Records(String id,String user_name,String first_name,String last_name,String email,String title) {
        this.user_name = user_name;
        this.title = title;
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.id = id;
    }

    @SerializedName("first_name")
    @Expose
    private String first_name;

    @SerializedName("last_name")
    @Expose
    private String last_name;

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getEmail1() {
        return email;
    }

    public void setEmail1(String email1) {
        this.email = email1;
    }

    @SerializedName("email1")
    @Expose
    private String email;

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @SerializedName("id")
    @Expose
    private String id;
}

1 Ответ

0 голосов
/ 07 мая 2020

Вы не можете установить любое значение 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...