RecyclerView не отображается, если Edittext не нажата или не сфокусирована на нагрузке - PullRequest
0 голосов
/ 12 декабря 2018

Я попробовал решение, предоставленное здесь: RecyclerView не показывает , но все еще не отображается, если не нажать кнопку Edittext.Данные вызываются из файла CSV с определенного URL.

MainActivity Код:

    //getting the recyclerview from xml
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    //getting CSV data from URL
    DownloadFilesTask downloadFilesTask = new DownloadFilesTask();
    downloadFilesTask.execute();

    //initializing the productlist
    productList = new ArrayList<>();

    //creating recyclerview adapter
    ProductAdapter adapter = new ProductAdapter(this, productList);
    adapter.notifyItemInserted(productList.size());
    adapter.notifyDataSetChanged();

    //setting adapter to recyclerview
    recyclerView.setAdapter(adapter);

XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".MainActivity">

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true">

<Spinner
    android:id="@+id/filter_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:entries="@array/filter_array"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:ems="10"
    android:inputType="text"
    android:text="Search"
    android:visibility="visible"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/filter_spinner" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible"
    app:layout_constraintTop_toBottomOf="@+id/editText"/>

Вот код для получения данных CSVс URL:

private class DownloadFilesTask extends AsyncTask<URL, Void, List<String[]>> {
    protected List<String[]> doInBackground(URL... urls) {
        return downloadRemoteTextFileContent();
    }
    protected void onPostExecute(List<String[]> result) {
        if(result != null){
            printCVSContent(result);
        }
    }
}

private void printCVSContent(List<String[]> result){
    String cvsColumn = "";
    String distanceKM;
    for (int i = 0; i < result.size(); i++){
        String [] rows = result.get(i);
        //cvsColumn += rows[0] + " " + rows[1] + " " + rows[2] + "\n";

        //adding some items to our list
        distanceKM = getDistance(latitude, longitude, Double.parseDouble(rows[2]),Double.parseDouble(rows[3]));
        productList.add(
                new Product(
                        rows[0],
                        rows[1].replace(';', ','),
                        rows[2],
                        rows[3],
                        rows[4],
                        rows[5],
                        rows[6],
                        distanceKM,
                        rows[7].replace(';', '\n')));

    }

Есть другие коды от адаптера продукта, которые, я думаю, не должны отображаться здесь.Источник, которым я пользуюсь, большинство кодов находится здесь: https://www.simplifiedcoding.net/android-recyclerview-cardview-tutorial/#RecyclerView-Item-Layout-using-CardView, где я просто объединяюсь со своим кодом.

1 Ответ

0 голосов
/ 12 декабря 2018

Поскольку DownloadFilesTask является AsyncTask, вы не можете быть уверены, что процесс добавления продуктов до этой строки завершен:

ProductAdapter adapter = new ProductAdapter(this, productList);

Вы можете просто инициализировать productList и адаптер в главном потокеперед вызовом AsyncTask.execute () ;А затем вызовите notifyDataSetChanged после выполнения AsyncTask.

...