Я создаю простое приложение-менеджер задач для своего исследования, но у меня возникла проблема с представлением корзины, в котором не отображаются все мои данные. Я добавил 3 разные таблицы, и в моем обзоре recyclerview отображается только первая. Надеялся, что вы, ребята, сможете помочь выяснить, в чем проблема. Большое спасибо за помощь
Это моя база данных, которая работает нормально
1 Тестирование 123 Тестирование, чтобы проверить, работает ли 17/5/2024
2 Тестирование 456 Тестирование 2-й раз 17.05.2024
3 Снова тестирование Тестирование проверка базы данных 31.05.2024
MainActivity.java
package com.example.a41p;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
ArrayList task_title, task_description, task_duedate;
CustomAdapter customAdapter;
@SuppressLint("CutPasteId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views
recyclerView = findViewById(R.id.recyclerview);
add_button = findViewById(R.id.floatingActionButton);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(view -> {
// Navigate back to MainActivity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // Finish current activity
});
// Set onClickListener for the FloatingActionButton
add_button.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
addActivityResultLauncher.launch(intent);
});
myDB = new MyDatabaseHelper(MainActivity.this);
task_title = new ArrayList();
task_description = new ArrayList();
task_duedate = new ArrayList();
// Store data from the database into the array
storeDataInArrays(false);
// Set up the RecyclerView with the CustomAdapter
customAdapter = new CustomAdapter(MainActivity.this, this, task_title, task_description, task_duedate);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
//I think is the problem but seems to look fine
private final ActivityResultLauncher addActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// Append new data to the RecyclerView
storeDataInArrays(true);
customAdapter.notifyDataSetChanged();
}
}
);
void storeDataInArrays(boolean append) {
Cursor cursor = myDB.readAllData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
} else {
if (!append) {
task_title.clear();
task_description.clear();
task_duedate.clear();
}
while (cursor.moveToNext()) {
task_title.add(cursor.getString(1));
task_description.add(cursor.getString(2));
task_duedate.add(cursor.getString(3));
}
}
}
}
мой Activity_main.xml
Вот как это выглядит
Я думаю, что проблема в этой части, поскольку я спрашивал об этом в чате, но он сказал, что все выглядит нормально, моя цель — просто распечатывать карточку каждый раз, когда я добавляю новую задачу.
private final ActivityResultLauncher addActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// Append new data to the RecyclerView
storeDataInArrays(true);
customAdapter.notifyDataSetChanged();
}
}
);
Это мой CustomAPdapter, который работает с xml my_row
package com.example.a41p;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter {
private final Context context;
private final Activity activity;
private final ArrayList task_title;
private final ArrayList task_description;
private final ArrayList task_duedate;
public CustomAdapter(Activity activity, Context context, ArrayList task_title, ArrayList task_description, ArrayList task_duedate) {
this.activity = activity;
this.context = context;
this.task_title = task_title;
this.task_description = task_description;
this.task_duedate = task_duedate;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
holder.task_title_txt.setText(task_title.get(position));
holder.task_description_txt.setText(task_description.get(position));
holder.task_duedate_txt.setText(task_duedate.get(position));
holder.mainLayout.setOnClickListener(view -> {
int adapterPosition = holder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("title", String.valueOf(task_title.get(adapterPosition)));
intent.putExtra("description", String.valueOf(task_description.get(adapterPosition)));
intent.putExtra("due date", String.valueOf(task_duedate.get(adapterPosition)));
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return task_title.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView task_title_txt, task_description_txt, task_duedate_txt;
LinearLayout mainLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
task_title_txt = itemView.findViewById(R.id.task_title_txt);
task_description_txt = itemView.findViewById(R.id.task_description_txt);
task_duedate_txt = itemView.findViewById(R.id.task_duedate_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
my_row.xml
Подробнее здесь: https://stackoverflow.com/questions/784 ... s-normally
RecyclerView не печатает все данные, когда файл базы данных работает нормально ⇐ Android
Форум для тех, кто программирует под Android
1715833019
Anonymous
Я создаю простое приложение-менеджер задач для своего исследования, но у меня возникла проблема с представлением корзины, в котором не отображаются все мои данные. Я добавил 3 разные таблицы, и в моем обзоре recyclerview отображается только первая. Надеялся, что вы, ребята, сможете помочь выяснить, в чем проблема. Большое спасибо за помощь
Это моя база данных, которая работает нормально
1 Тестирование 123 Тестирование, чтобы проверить, работает ли 17/5/2024
2 Тестирование 456 Тестирование 2-й раз 17.05.2024
3 Снова тестирование Тестирование проверка базы данных 31.05.2024
MainActivity.java
package com.example.a41p;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
MyDatabaseHelper myDB;
ArrayList task_title, task_description, task_duedate;
CustomAdapter customAdapter;
@SuppressLint("CutPasteId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views
recyclerView = findViewById(R.id.recyclerview);
add_button = findViewById(R.id.floatingActionButton);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(view -> {
// Navigate back to MainActivity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // Finish current activity
});
// Set onClickListener for the FloatingActionButton
add_button.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
addActivityResultLauncher.launch(intent);
});
myDB = new MyDatabaseHelper(MainActivity.this);
task_title = new ArrayList();
task_description = new ArrayList();
task_duedate = new ArrayList();
// Store data from the database into the array
storeDataInArrays(false);
// Set up the RecyclerView with the CustomAdapter
customAdapter = new CustomAdapter(MainActivity.this, this, task_title, task_description, task_duedate);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
//I think is the problem but seems to look fine
private final ActivityResultLauncher addActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// Append new data to the RecyclerView
storeDataInArrays(true);
customAdapter.notifyDataSetChanged();
}
}
);
void storeDataInArrays(boolean append) {
Cursor cursor = myDB.readAllData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
} else {
if (!append) {
task_title.clear();
task_description.clear();
task_duedate.clear();
}
while (cursor.moveToNext()) {
task_title.add(cursor.getString(1));
task_description.add(cursor.getString(2));
task_duedate.add(cursor.getString(3));
}
}
}
}
мой Activity_main.xml
Вот как это выглядит
Я думаю, что проблема в этой части, поскольку я спрашивал об этом в чате, но он сказал, что все выглядит нормально, моя цель — просто распечатывать карточку каждый раз, когда я добавляю новую задачу.
private final ActivityResultLauncher addActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// Append new data to the RecyclerView
storeDataInArrays(true);
customAdapter.notifyDataSetChanged();
}
}
);
Это мой CustomAPdapter, который работает с xml my_row
package com.example.a41p;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter {
private final Context context;
private final Activity activity;
private final ArrayList task_title;
private final ArrayList task_description;
private final ArrayList task_duedate;
public CustomAdapter(Activity activity, Context context, ArrayList task_title, ArrayList task_description, ArrayList task_duedate) {
this.activity = activity;
this.context = context;
this.task_title = task_title;
this.task_description = task_description;
this.task_duedate = task_duedate;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
holder.task_title_txt.setText(task_title.get(position));
holder.task_description_txt.setText(task_description.get(position));
holder.task_duedate_txt.setText(task_duedate.get(position));
holder.mainLayout.setOnClickListener(view -> {
int adapterPosition = holder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("title", String.valueOf(task_title.get(adapterPosition)));
intent.putExtra("description", String.valueOf(task_description.get(adapterPosition)));
intent.putExtra("due date", String.valueOf(task_duedate.get(adapterPosition)));
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return task_title.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView task_title_txt, task_description_txt, task_duedate_txt;
LinearLayout mainLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
task_title_txt = itemView.findViewById(R.id.task_title_txt);
task_description_txt = itemView.findViewById(R.id.task_description_txt);
task_duedate_txt = itemView.findViewById(R.id.task_duedate_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
my_row.xml
Подробнее здесь: [url]https://stackoverflow.com/questions/78487547/recyclerview-is-not-priting-all-the-data-when-the-database-file-works-normally[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия