recyclerview会消失

gt0wga4j  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(358)

我正在做一个android应用程序,上面有一个edittext,按钮上有一个recyclerview。
每当用户在edittext字段中点击“enter”时,我就会用okhttp进行api调用,并将所需的信息保存到一个singleton类中,这样我的适配器就可以使用它并更新列表。
但是,如果焦点不在edittext中,则不会显示(更新)recyclerview

“v/viewrootimpl:指定的消息队列同步屏障令牌尚未发布或已被删除”每当我单击edittext时,它都会显示这一点,我在google中发现它可能是线程问题。我与线程交互的唯一地方是我用okhttp发出的api请求。但是,请求返回并正确解释json文件。

public Boolean makeCall (String parameter) throws IOException, UnirestException {

    // make the api call
    String completedLink = BASE_LINK + parameter;
    Future<HttpResponse<com.mashape.unirest.http.JsonNode>> response = Unirest.get("https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=wat")
            .header("x-rapidapi-host", "mashape-community-urban-dictionary.p.rapidapi.com")
            .header("x-rapidapi-key", "xxxxx")
            .asJsonAsync(new Callback<com.mashape.unirest.http.JsonNode>() {
                @Override
                public void completed(HttpResponse<com.mashape.unirest.http.JsonNode> response) {
                    // decode the response body
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode node = null;
                    try {
                        node = objectMapper.readTree(String.valueOf(response.getBody()));
                    } catch (JsonProcessingException ex) {
                        ex.printStackTrace();
                    }
                    JsonNode resultNode = node.get("list");
                    List<WordItem> resultList = null;
                    try {
                        resultList = objectMapper.readValue(resultNode.toString(),
                                new TypeReference<List<WordItem>>() {});
                    } catch (JsonProcessingException ex) {
                        ex.printStackTrace();
                    }
                    SavedInfo.getInstance().setResult(resultList);
                }

                @Override
                public void failed(UnirestException e) {

                }

                @Override
                public void cancelled() {

                }
            });

    return true;
}

每当我在软键盘上按enter键时,我的代码就会开始进行api调用

mResult.setAdapter(adapter);
    mResult.setNestedScrollingEnabled(false);
    mResult.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    mResult.setLayoutManager(new LinearLayoutManager(getContext()));

    mSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                    if (i == EditorInfo.IME_ACTION_DONE) {

                        // show progress bar
                        hideProgressBar(false, mProgress);

                        mHomeText.setText(textView.getText());
                        try {
                            if (new HttpRequest().makeCall(textView.getText().toString())){
                                adapter.updateList();
                            }
                            else {
                                // showing error message
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            return false;
                        }
                        hideProgressBar(true, mProgress);

                        // hide keyword when enter key is detected
                        View view = getActivity().getCurrentFocus();
                        if (view != null) {
                            InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        }
                    }
                    return true;
                }
    });

另外,需要指出的一点是进度条(我将其设置为“可见”,但不显示仍然)根本没有显示。我在代码中设置了一些地方,singleton类和http请求是正确的,并且返回+保存正确的信息。
这是我的适配器类中的updatelist(),以防万一

public void updateList () {
    list.clear();
    list.addAll(SavedInfo.getInstance().getResult());
    notifyDataSetChanged();
  }

这是我的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".ui.home.HomeFragment"
    android:orientation="vertical">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#F3F3F3"
        app:layout_constraintStart_toStartOf="parent">

        <TextView
            android:id="@+id/title_word_home"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="36dp"
            android:fontFamily="sans-serif"
            android:text="@string/home_text"
            android:textAlignment="center"
            android:textSize="28sp"
            android:textStyle="bold"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout_editor_absoluteX="0dp" />

        <EditText
            android:id="@+id/searchBox"
            android:layout_width="254dp"
            android:layout_height="50dp"
            android:layout_marginStart="239dp"
            android:layout_marginEnd="239dp"
            android:autofillHints=""
            android:drawableStart="@drawable/ic_search"
            android:drawablePadding="10dp"
            android:ems="10"
            android:hint="@string/searchBox_hint"
            android:imeOptions="actionDone"
            android:inputType="text"
            android:pointerIcon="none"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/title_word_home" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/loading_progress"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center|center_vertical"
            android:indeterminate="true"
            android:visibility="gone" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/home_resultList"
            android:layout_width="409dp"
            android:layout_height="wrap_content"
            android:visibility="visible" />

    </LinearLayout>

</LinearLayout>

谢谢你的阅读!

z2acfund

z2acfund1#

出现此问题的原因是,数据在下载之前发布到回收器视图。您正在尝试更新方法中的回收器视图 updateList() 它在请求启动后但在请求完成之前调用。这也是为什么进度条没有显示-它马上就消失了。
为了解决这个问题,你必须触发 updateList() 数据下载后。最好的办法是重写 makeCall() 方法,它接受第二个参数作为回调,因此可以更新列表。
定义自定义回调:

interface MyCallback {

    void completed(List<WordItem> result);
    void error(UnirestException error);
}

重写一下打电话:

public void makeCall(String parameter, MyCallback callback) {

    // make the api call
    String completedLink = BASE_LINK + parameter;
    Future<HttpResponse<com.mashape.unirest.http.JsonNode>> response = Unirest.get("https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=wat")
        .header("x-rapidapi-host", "mashape-community-urban-dictionary.p.rapidapi.com")
        .header("x-rapidapi-key", "xxxxx")
        .asJsonAsync(new Callback<com.mashape.unirest.http.JsonNode>() {
            @Override
            public void completed(HttpResponse<com.mashape.unirest.http.JsonNode> response) {
                // decode the response body
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode node = null;
                try {
                    node = objectMapper.readTree(String.valueOf(response.getBody()));
                } catch (JsonProcessingException ex) {
                    ex.printStackTrace();
                }
                JsonNode resultNode = node.get("list");
                List<WordItem> resultList = null;
                try {
                    resultList = objectMapper.readValue(resultNode.toString(),
                            new TypeReference<List<WordItem>>() {});
                } catch (JsonProcessingException ex) {
                    ex.printStackTrace();
                }
                // SavedInfo.getInstance().setResult(resultList);
                callback.completed(resultList);
            }

            @Override
            public void failed(UnirestException e) {
                callback.failed(e);
            }

            @Override
            public void cancelled() {

            }
        });

}
最后将回调传递给 makeCall() 并刷新列表:

@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
    if (i == EditorInfo.IME_ACTION_DONE) {

        // show progress bar
        hideProgressBar(false, mProgress);

        // clear your list before call if you wish
        // updateList(null);

        mHomeText.setText(textView.getText());

        new HttpRequest().makeCall(textView.getText().toString(), new MyCallback() {

            @Override
            public void completed(List<WordItem> result) {
                updateList(result);
                hideProgressBar(true, mProgress);
            }

            @Override
            public void error(UnirestException error) {
                hideProgressBar(true, mProgress);

                // showing error message
            }
        });

        // hide keyword when enter key is detected
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    return true;
}

此方法也应重写:

public void updateList(List<WordItem> result) {
    list.clear();
    if (result != null) list.addAll(result);
    notifyDataSetChanged();
}

在那之后,问题应该消失了,而且你不再需要在singleton类中保存你的数据。
顺便说一句,这里有一个改装库,用于以更简单的方式发出api请求。这种改进是android社区的最佳实践,所以我建议尝试使用它。

相关问题