Room - Невозможно отобразить полный список базы данных - PullRequest
0 голосов
/ 21 февраля 2020

Я новичок в Android и Комнате и до сих пор не могу в полной мере понять это - буду благодарен за любую помощь. База данных создана и все запросы работают, данные вставляются в таблицу (как показано Стето). Проблема в том, что я не могу отобразить все содержимое таблицы в своей активности - она ​​показывает только последнюю вставку. Вот действие, в котором я выполняю запросы

public class ShowDatabaseActivity extends AppCompatActivity {
    private List<Contact> allContacts = new ArrayList<>();
    public ContactsListAdapter adapter;
    private ContactDao contactDao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
        Intent intent = getIntent();
        unpack(intent);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        adapter = new ContactsListAdapter(allContacts, ShowDatabaseActivity.this);
        adapter.notifyDataSetChanged();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }

    private void unpack(Intent intent) {
        Bundle extras = intent.getExtras();
        String lastName = extras.getString(Constants.LAST_NAME_KEY);
        String firstName = extras.getString(Constants.FIRST_NAME_KEY);
        String middleName = extras.getString(Constants.MIDDLE_NAME_KEY);
        int age = extras.getInt(Constants.AGE_KEY);
        Contact contact = new Contact(lastName, firstName, middleName, age);
        final Handler handler = new Handler();
        Thread backgroundThread = new Thread(new Runnable() {
            @Override
            public void run() {
                AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().insert(contact);
                AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAlphabetizedContacts();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.addItem(contact);
                    }
                });
            }
        });
        backgroundThread.start();
    }
}

И мой Adaper



public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;
    private LayoutInflater inflater;

    public ContactsListAdapter(@NonNull List<Contact> contacts, Context context) {
        this.contacts = contacts;
        inflater = LayoutInflater.from(context);
        this.context = context;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }


    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
        Contact currentContact = contacts.get(position);
        if (currentContact != null) {
            holder.contactLastNameView.setText(currentContact.getLastName());
            holder.contactFirstNameView.setText(currentContact.getFirstName());
            holder.contactMiddleNameView.setText(currentContact.getMiddleName());
            holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
        } else {
            holder.contactLastNameView.setText("No information");
            holder.contactFirstNameView.setText("No information");
            holder.contactMiddleNameView.setText("No information");
            holder.contactAgeView.setText("No information");
        }
    }

    @Override
    public int getItemCount() {
        return contacts.size();
    }

    class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        private ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    public void addItem(Contact contact) {
        contacts.add(contact);
        notifyItemInserted(contacts.size() - 1);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(final int position) {
        return R.layout.recycler_view;
    }
}

И моя база данных

package com.example.sqliteorm;
import android.content.Context;
import android.util.Log;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import java.util.List;

@Database(entities = {Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract ContactDao contactDao();

    private List<Contact> allContacts;

    List<Contact> getAllContacts() {
        return allContacts;
    }

    private static AppDatabase INSTANCE;

    public synchronized static AppDatabase getINSTANCE(Context context) {
        INSTANCE = getDatabase(context);
        return INSTANCE;
    }

    static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        AppDatabase.class, "table_contacts")
                        .build();
                Log.d("LOG", "Getting the database instance");
            }
        }
        return INSTANCE;
    }
}

Мой класс констант

    public final static String LAST_NAME_KEY = "LAST_NAME_KEY";
    public final static String FIRST_NAME_KEY = "FIRST_NAME_KEY";
    public final static String MIDDLE_NAME_KEY = "MIDDLE_NAME_KEY";
    public final static String AGE_KEY = "AGE_KEY";

    private Constants() {
    }
}```
My queries seem to be good as I used them in different version of database - so do not post them
 I will greatly appreciate any help!
...