I trying to find a way to save the state of checkbox to Room Database.But when I click on checkbox and reopen the app,it's state doesn't change.I don't know where I went wrong.
I have searched the previous questions but could not find the solution. Below is my code and thanks.
Model class
#Entity(tableName = "todo_table")
public class Todo {
#PrimaryKey(autoGenerate = true)
public int id;
public String title;
public Boolean isChecked;
public Todo(String title, Boolean isChecked) {
this.title = title;
this.isChecked = isChecked;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getChecked() {
return isChecked;
}
public void setChecked(Boolean checked) {
isChecked = checked;
}
}
DAO
#Dao
public interface TodoDAO {
#Insert
void Insert(Todo todo);
#Update
void Update(Todo todo);
#Query("SELECT * FROM todo_table ORDER BY id ASC")
LiveData<List<Todo>> getAllTodo();
}
TodoDatabase
#Database(entities = Todo.class,version = 1,exportSchema = false)
public abstract class TodoDatabase extends RoomDatabase {
private static TodoDatabase instance;
public abstract TodoDAO todoDAO();
public static synchronized TodoDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
TodoDatabase.class,"todo_database").fallbackToDestructiveMigration()
.addCallback(roomCallBack)
.build();
}
return instance;
}
private static RoomDatabase.Callback roomCallBack = new RoomDatabase.Callback(){
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDbAsyncTask(instance).execute();
}
};
private static class PopulateDbAsyncTask extends AsyncTask<Void,Void,Void> {
private TodoDAO todoDAO;
private PopulateDbAsyncTask(TodoDatabase database) {
todoDAO = database.todoDAO();
}
#Override
protected Void doInBackground(Void... voids) {
return null;
}
}
}
TodoRepository
public class TodoRepository {
private TodoDAO todoDAO;
private LiveData<List<Todo>> todo;
public TodoRepository(Application application){
TodoDatabase database = TodoDatabase.getInstance(application);
todoDAO = database.todoDAO();
todo = todoDAO.getAllTodo();
}
public void insert(Todo todo){
new InsertNoteAsyncTask(todoDAO).execute(todo);
}
public LiveData<List<Todo>> getTodo() {
return todo;
}
public void update(Todo todo){
new UpdateTodoAsyncTask(todoDAO).execute(todo);
}
private static class InsertNoteAsyncTask extends AsyncTask<Todo,Void,Void> {
private TodoDAO todoDAO;
private InsertNoteAsyncTask(TodoDAO todoDAO){
this.todoDAO = todoDAO;
}
#Override
protected Void doInBackground(Todo... todos) {
todoDAO.Insert(todos[0]);
return null;
}
}
private static class UpdateTodoAsyncTask extends AsyncTask<Todo,Void,Void> {
private TodoDAO todoDAO;
private UpdateTodoAsyncTask(TodoDAO todoDAO){
this.todoDAO = todoDAO;
}
#Override
protected Void doInBackground(Todo... todos) {
todoDAO.Update(todos[0]);
return null;
}
}
}
TodoViewModel
public class TodoViewModel extends AndroidViewModel {
private TodoRepository repository;
private LiveData<List<Todo>> todo;
public TodoViewModel(#NonNull Application application) {
super(application);
repository = new TodoRepository(application);
todo = repository.getTodo();
}
public void insert(Todo todo){
repository.insert(todo);
}
public void update(Todo todo){
repository.update(todo);
}
public LiveData<List<Todo>> getTodo(){
return todo;
}
}
TodoAdapter
public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.ViewHolder>{
private List<Todo> todos = new ArrayList<>();
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(TodoItemBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false));
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Todo currentTodo = todos.get(holder.getAbsoluteAdapterPosition());
holder.binding.tvTitle.setText(currentTodo.getTitle());
holder.binding.checkBox.setChecked(currentTodo.getChecked());
holder.binding.checkBox.setOnCheckedChangeListener(null);
holder.binding.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
holder.binding.checkBox.setChecked(true);
}else{
holder.binding.checkBox.setChecked(false);
}
}
});
}
#Override
public int getItemCount() {
if(todos != null){
return todos.size();
}else{
return 0;
}
}
public void setTodos(List<Todo> todos){
this.todos = todos;
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TodoItemBinding binding;
public ViewHolder(TodoItemBinding bind){
super(bind.getRoot());
this.binding = bind;
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private TodoItemBinding todoItemBinding;
private TodoViewModel todoViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
todoItemBinding = TodoItemBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
RecyclerView recyclerView = binding.recyclerView;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
TodoAdapter todoAdapter = new TodoAdapter();
recyclerView.setAdapter(todoAdapter);
todoViewModel = new ViewModelProvider(this).get(TodoViewModel.class);
todoViewModel.getTodo().observe(this, new Observer<List<Todo>>() {
#Override
public void onChanged(List<Todo> todos) {
todoAdapter.setTodos(todos);
}
});
binding.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTodo();
}
});
todoItemBinding.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean isChecked = todoItemBinding.checkBox.isChecked();
Todo todo;
if (isChecked){
todo = new Todo(binding.editText.getText().toString(), true);
}else{
todo = new Todo(binding.editText.getText().toString(), false);
}
todoViewModel.update(todo);
}
});
}
private void addTodo() {
String title = binding.editText.getText().toString();
Todo todo = new Todo(title,false);
todoViewModel.insert(todo);
binding.editText.setText("");
closeKeyboard();
}
private void closeKeyboard(){
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
Using SharedPrefs would save a lot of time. Change the following code:
Inside MainActivity
public void onClick(View v) {
Boolean isChecked = todoItemBinding.checkBox.isChecked();
Todo todo;
if (isChecked){
todo = new Todo(binding.editText.getText().toString(), true);
}else{
todo = new Todo(binding.editText.getText().toString(), false); }
todoViewModel.update(todo);
}
with this
public void onClick(View v) {
Boolean isChecked =PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("checkBox1", false);
checkBox1.setChecked(checked);
Todo todo;
if (isChecked){
todo = new Todo(binding.editText.getText().toString(), true);
}else{
todo = new Todo(binding.editText.getText().toString(), false); }
todoViewModel.update(todo);
}
Related
Idk why is it not working, Im trying to transfer data, i'm doing an app but when i run it i get an error, the Error is in the BlogActivity Class
"showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));"(java.lang.NullPointerException).
This is BlogActivity Class:
public class BlogActivity extends AppCompatActivity{
private static final String EXTRAS_BLOG = "EXTRAS_BLOG";
private TextView textTitle;
private TextView textDate;
private TextView textAuthor;
private TextView textRating;
private TextView textDescription;
private TextView textViews;
private RatingBar ratingBar;
private ImageView imageAvatar;
private ImageView imageMain;
private ImageView imageBack;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpage);
imageMain = findViewById(R.id.yemenImg);
imageAvatar = findViewById(R.id.yemenAvatar);
imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent myInt = new Intent(getApplicationContext(),MainActivity.class);
startActivity(myInt);
}
},2);
}
});
textDate = findViewById(R.id.dateYemen);
textTitle = findViewById(R.id.textTitle);
textAuthor = findViewById(R.id.yemenAuthor);
textRating = findViewById(R.id.textRating);
textViews = findViewById(R.id.textViews);
textDescription = findViewById(R.id.textDescription);
ratingBar = findViewById(R.id.ratingBar);
progressBar = findViewById(R.id.progressBar);
showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));
}
/*private void loadData()
{
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showData(blogList.get(0));
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showErrorSnackbar();
}
});
}
});
}*/
private void showData(Blog blog)
{
progressBar.setVisibility(View.GONE);
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
textAuthor.setText(blog.getAuthor().getName());
textRating.setText(String.valueOf(blog.getRating()));
textViews.setText(String.format("(%d views)", blog.getViews()));
textDescription.setText(blog.getDescription());
textDescription.setText(Html.fromHtml(blog.getDescription(),Html.FROM_HTML_MODE_COMPACT));
ratingBar.setRating(blog.getRating());
ratingBar.setVisibility(View.VISIBLE);
imageBack.setImageResource(R.drawable.ic_baseline_arrow_back_24);
Glide.with(this)
.load(blog.getImage())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageMain);
Glide.with(this)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
/*private void showErrorSnackbar()
{
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
snackbar.dismiss();
});
snackbar.show();
}*/
public static void startBlogDetailsActivity(Activity activity, Blog blog) {
Intent intent = new Intent(activity, BlogActivity.class);
intent.putExtra(EXTRAS_BLOG, blog);
activity.startActivity(intent);
}
Blog Class:
public class Blog implements Parcelable {
private String id;
private Author author;
private String title;
private String date;
private String image;
private String description;
private int views;
private float rating;
protected Blog(Parcel in) {
id = in.readString();
title = in.readString();
date = in.readString();
image = in.readString();
description = in.readString();
views = in.readInt();
rating = in.readFloat();
author = in.readParcelable(Author.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(date);
dest.writeString(image);
dest.writeString(description);
dest.writeInt(views);
dest.writeFloat(rating);
dest.writeParcelable(author, 0);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Blog> CREATOR = new Creator<Blog>() {
#Override
public Blog createFromParcel(Parcel in) {
return new Blog(in);
}
#Override
public Blog[] newArray(int size) {
return new Blog[size];
}
};
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
public int getViews() {
return views;
}
public float getRating() {
return rating;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Blog blog = (Blog) o;
return views == blog.views &&
Float.compare(blog.rating, rating) == 0 &&
Objects.equals(id, blog.id) &&
Objects.equals(author, blog.author) &&
Objects.equals(title, blog.title) &&
Objects.equals(date, blog.date) &&
Objects.equals(image, blog.image) &&
Objects.equals(description, blog.description);
}
#Override
public int hashCode() {
return Objects.hash(id, author, title, date, image, description, views, rating);
}
This is Main Activity Class:
public class MainActivity extends AppCompatActivity {
private MainAdapter adapter;
private SwipeRefreshLayout refreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainAdapter(blog ->
BlogActivity.startBlogDetailsActivity(this, blog));
RecyclerView recyclerView = findViewById(R.id.recylerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
refreshLayout = findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this::loadData);
loadData();
}
private void loadData()
{
refreshLayout.setRefreshing(true);
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
adapter.submitList(blogList);
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
showErrorSnackbar();
}
});
}
});
}
private void showErrorSnackbar() {
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
loadData();
snackbar.dismiss();
});
snackbar.show();
}
This is MainAdapter Class:
public class MainAdapter extends ListAdapter<Blog, MainAdapter.MainViewHolder>{
public interface OnItemClickListener{
void onItemClicked(Blog blog);
}
private OnItemClickListener clickListener;
public MainAdapter(OnItemClickListener clickListener){
super(DIFF_CALLBACK);
this.clickListener = clickListener;
}
#NonNull
#Override
public MainAdapter.MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_listlayout,parent,false);
return new MainViewHolder(view, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.MainViewHolder holder, int position)
{
holder.bindTo(getItem(position));
}
static class MainViewHolder extends RecyclerView.ViewHolder
{
private TextView textTitle;
private TextView textDate;
private ImageView imageAvatar;
private Blog blog;
public MainViewHolder(#NonNull View itemView, OnItemClickListener listener)
{
super(itemView);
itemView.setOnClickListener(view -> listener.onItemClicked(blog));
textTitle = itemView.findViewById(R.id.textTitle);
textDate = itemView.findViewById(R.id.textDate);
imageAvatar = itemView.findViewById(R.id.imageAvatar);
}
void bindTo(Blog blog)
{
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
Glide.with(itemView)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
}
private static final DiffUtil.ItemCallback<Blog> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Blog>()
{
#Override
public boolean areItemsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.getId().equals(newItem.getId());
}
#Override
public boolean areContentsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.equals(newItem);
}
};
You may set value to blog variable in MainViewHolder.
Add this line to your bindTo() method body:
this.blog = blog
I am learning Room DataBase!!
I Know How to Insert and Retrieve Data from Room DataBase to Recycler View!! But In Delete Operation I am getting error of "No Adapter attached Skipped Layout!"
What I want when anyone click on delete button on recycler view . The Task should be deleted
That's why I also Used delete method in Interface and add Interface in Recycler View Adapter which give call back to MainActivity so that we delete and update the recycler view
All of my codes are given below
Here is my Entity Class named as Task
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "task_name")
private String task_name;
#ColumnInfo
private String task_desc;
#ColumnInfo
private String comment;
#ColumnInfo
private String task_comp_date;
#ColumnInfo
private String activate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public String getTask_desc() {
return task_desc;
}
public void setTask_desc(String task_desc) {
this.task_desc = task_desc;
}
public String getTask_comp_date() {
return task_comp_date;
}
public void setTask_comp_date(String task_comp_date) {
this.task_comp_date = task_comp_date;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getActivate() {
return activate;
}
public void setActivate(String activate) {
this.activate = activate;
}
}
My Data Accession Object named as TaskDao
#Dao
public interface TaskDao {
#Query("SELECT * FROM task")
List<Task> getAll();
#Insert
void insert(Task task);
#Delete
void delete(Task task);
#Update
void update(Task task);
}
My DataBase
#Database(entities = {Task.class},version = 1)
public abstract class AppDataBase extends RoomDatabase {
public abstract TaskDao taskDao();
}
My DataBaseClient named as DatabaseClient
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstace;
private AppDataBase appDataBase;
public DatabaseClient(Context context) {
this.context = context;
appDataBase = Room.databaseBuilder(context,AppDataBase.class,"MyDailyTask").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstace == null)
{
mInstace = new DatabaseClient(context);
}
return mInstace;
}
public AppDataBase getAppDataBase()
{
return appDataBase;
}
}
My RecyclerView Adapter
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.MyViewHolder> {
private Context context;
private List<Task> taskList;
public interface OnDeleteClickListener
{
void OnDeleteClickListener(Task task);
}
private OnDeleteClickListener onDeleteClickListener;
public TaskAdapter(Context context, List<Task> taskList) {
this.context = context;
this.taskList = taskList;
}
public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) {
this.onDeleteClickListener = onDeleteClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(context).inflate(R.layout.view_task_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(taskList.get(position).getTask_name(),taskList.get(position).getTask_desc(),taskList.get(position).getComment(),taskList.get(position).getTask_comp_date(),position);
}
#Override
public int getItemCount() {
return taskList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView t1,t2,t3,t4,t5;
private ImageView view;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
t1= itemView.findViewById(R.id.tvCommnt);
t2=itemView.findViewById(R.id.tvDesc);
t3=itemView.findViewById(R.id.tvName);
t4= itemView.findViewById(R.id.tvStart);
t5 = itemView.findViewById(R.id.tvEnd);
view =itemView.findViewById(R.id.tvdele);
}
public void setData(String t01, String t02, String t03, String t05, final int position)
{
t1.setText("Task Comment "+t03);
t2.setText("Task Description "+t02);
t3.setText("Task Name "+ t01);
t4.setText("Start ");
t5.setText("Ënd "+t05);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onDeleteClickListener!=null)
{
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
taskList.remove(position);
notifyDataSetChanged();
}
}
});
}
}
}
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.ivAdd);
recyclerView = findViewById(R.id.rvTask);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddTaskActivity.class));
}
});
new newTask().execute();
}
class newTask extends AsyncTask<Void,Void, List<Task>> implements TaskAdapter.OnDeleteClickListener {
List<Task> tasks;
#Override
protected List<Task> doInBackground(Void... voids) {
tasks = DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().getAll();
return tasks;
}
#Override
protected void onPostExecute(List<Task> tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this,tasks);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
taskAdapter.setOnDeleteClickListener(this);
}
#Override
public void OnDeleteClickListener(final Task task) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
},1000);
}
}
welcome in stack
you interface is declared but not assign so your will throw null pointer when click on item inside your list, but good work your check null before fire method interface
first add setter for OnDeleteClickListener inside your adapter
public void setOnDeleteClickListener(OnDeleteClickListener listener){
this.onDeleteClickListener=listener;
}
and also add code that remove item from you list when user click item
so inside setData method update this code
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onDeleteClickListener != null) {
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
//remove item from list and then notify adapter data is changed
taskList.remove(position);
notifyDataSetChanged();
}
}
});
finally to Triggers onDeleteClickListener inside your AsyncTask
update your code here
#Override
protected void onPostExecute(List < Task > tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this, tasks, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
//pass this that refer to my interface
taskAdapter.setOnDeleteClickListener(this);
}
inside your OnDelete just use this code to run in another thread
AsyncTask.execute(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
});
Advice : Don't name your variable or arguments like String
t01,String t02..etc ,choice name for like what this variable jop
like String taskComment,String taskName ..etc
i hope this help you
I can't understand why it makes problem with it. It take data from server with retrofit and it can't use that data in recyclerview. It make problem with Constructor but I can not understand why it makes problem with it. That can get data from service successfully with this Model, but problem is to put adapter and recyclierview. How can solve it?
ProductPage.java
public class ProductPage {
private int productID;
private String productName;
private String productDescription;
private List<String> productImages;
private List<ProductPrice> productPrices;
public int getProductID() {
return productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public List<String> getProductImages() {
return productImages;
}
public void setProductImages(List<String> productImages) {
this.productImages = productImages;
}
public List<ProductPrice> getProductPrices() {
return productPrices;
}
public void setProductPrices(List<ProductPrice> productPrices) {
this.productPrices = productPrices;
}
}
ProductDetailAdapter.java
public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.ViewHolder> {
private Context mContext;
int rawLayout;
private List<ProductPage> productPageList;
private int cartAmount;
public ProductDetailAdapter(Context mContext,int rawLayout, List<ProductPage> productPageList, CartListener cartListener) {
this.mContext = mContext;
this.rawLayout = rawLayout;
this.productPageList = productPageList;
this.cartListener = cartListener;
}
#NonNull
#Override
public ProductDetailAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View mView = LayoutInflater.from(parent.getContext()).inflate(rawLayout, parent, false);
return new ViewHolder(mView); }
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
Glide.with(mContext).load(productPageList.get(position).getProductPrices().get(position).getShopImage())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(viewHolder.imgProductDetail);
viewHolder.textProductDetailCost.setText(Double.toString(productPageList
.get(position).getProductPrices().get(position).getShopProductPrice())+" TL");
viewHolder.textProductDetailMarket.setText(productPageList.get(position).getProductPrices().get(position).getShopName());
}
#Override
public int getItemCount() {
return productPageList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imgProductDetail;
private TextView textProductDetailCost, textProductDetailMarket;
private Button btnProductDetail;
private CardView cardViewProductDetail;
ViewHolder(View itemView){
super(itemView);
imgProductDetail = itemView.findViewById(R.id.imageView_product_detail);
textProductDetailCost = itemView.findViewById(R.id.text_product_detail_cost);
textProductDetailMarket = itemView.findViewById(R.id.textViewProductShopName);
btnProductDetail = itemView.findViewById(R.id.buttonProductDetail);
cardViewProductDetail = itemView.findViewById(R.id.cardViewProductDetail);
}
}
public interface CartListener {
void onProductSelect(ProductPage productPage);
}
}
ProductActivity.java
public class ProductActivity extends AppCompatActivity implements ProductDetailAdapter.CartListener {
TextView textProductName, textDescription;
RecyclerView recyclerViewProduct;
protected RecyclerView.LayoutManager mLayoutManager;
String productCost, productMarket, productImage, productTitle, prdouctMarketImage;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
init();
loadProductPage();
}
private void init() {
textProductName = findViewById(R.id.text_product_title);
imgProduct = findViewById(R.id.img_product);
recyclerViewProduct = findViewById(R.id.product_recycylerwiew);
textDescription = findViewById(R.id.text_product_description);
textDescription.setMovementMethod(new ScrollingMovementMethod()); // Scroll yapabilmek için açmıştım
mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewProduct.setLayoutManager(mLayoutManager);
private void loadProductPage() {
ApiInterface apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<ProductPage> call = apiInterface.getProductPage(id);
call.enqueue(new Callback<ProductPage>() {
#Override
public void onResponse(Call<ProductPage> call, Response<ProductPage> response) {
if (response.isSuccessful()) {
ProductPage product_page_list = response.body();
textProductName.setText(product_page_list.getProductName());
textDescription.setText(product_page_list.getProductDescription());
Glide.with(getApplicationContext()).load(product_page_list.getProductImages())
.apply(RequestOptions.placeholderOf(R.drawable.ic_glide_img).error(R.drawable.ic_glide_warning)).
into(imgProduct);
ProductDetailAdapter myAdapter = new ProductDetailAdapter(getApplicationContext(),R.layout.product_detail_item_view,product_page_list,ProductActivity.this);
recyclerViewProduct.setAdapter(myAdapter);
}
else
ApiErrorUtils.parseError(response);
}
#Override
public void onFailure(Call<ProductPage> call, Throwable t) {
Log.d("response","apiError");
}
});
}
#Override
public void onProductSelect(ProductPage productPage) {
}
You are just passing ProductPage object to adapter.
ProductPage product_page_list = response.body();
but your adapter required
List<ProductPage> productPageList
So you need to add product object to product list like this
ProductPage productPage = response.body();
List<ProductPage> productList=new ArrayList<>();
productList.add(productPage);
ProductPage product_page_list = response.body();
product_page_list is not List<ProductPage>()
in your adapter need List<ProductPage> productPageList
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
I am trying to develop an application that uses Room Persistence Database and displays a list on a RecyclerView, I've followed Google's tutorials and everything but I can seem to see the items on the screen, the app doesn't crash or anything just nothing appearing on the scree:
Here is the Data object class:
#Entity(tableName = "region")
public class Region {
#NonNull
#PrimaryKey(autoGenerate = true)
private int mId;
#ColumnInfo(name = "region_name")
private String mRegionName;
#ColumnInfo(name = "association")
private String mAssociation;
#ColumnInfo(name = "season")
private String mSeason;
public Region(#NonNull int id, String regionName, String association, String season) {
mId = id;
mRegionName = regionName;
mAssociation = association;
mSeason = season;
}
#NonNull
public int getId() {
return mId;
}
public void setId(#NonNull int id) {
mId = id;
}
public String getRegionName() {
return mRegionName;
}
public void setRegionName(String regionName) {
mRegionName = regionName;
}
public String getAssociation() {
return mAssociation;
}
public void setAssociation(String association) {
mAssociation = association;
}
public String getSeason() {
return mSeason;
}
public void setSeason(String season) {
mSeason = season;
}
Here is the Data Dao:
#Dao
public interface RegionDao {
#Query("SELECT * FROM region")
List<Region> getAll();
#Insert
void insert(Region... region);
#Query("DELETE FROM region")
void deleteAll();
Here is the Adapter Class:
public class RegionsAdapter extends RecyclerView.Adapter<RegionsAdapter.RegionViewHolder> {
private List<Region> mRegionList;
private Context mContext;
private int mRowLayout;
private RecyclerViewClickListener mListener;
public static class RegionViewHolder extends RecyclerView.ViewHolder{
LinearLayout regionLayout;
TextView regionName, regionAss, regionSeason;
public RegionViewHolder(View v, RecyclerViewClickListener listener){
super(v);
regionLayout = v.findViewById(R.id.region_layout);
regionName = v.findViewById(R.id.region_name);
regionAss = v.findViewById(R.id.region_ass);
regionSeason = v.findViewById(R.id.region_season);
}
}
public void setClickListener(RecyclerViewClickListener recyclerViewClickListener){
mListener = recyclerViewClickListener;
}
public RegionsAdapter(List<Region> regionList, Context context, int rowLayout, RecyclerViewClickListener listener) {
mRegionList = regionList;
mContext = context;
mRowLayout = rowLayout;
mListener = listener;
}
#Override
public RegionsAdapter.RegionViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(mRowLayout, parent, false);
final RegionsAdapter.RegionViewHolder holder = new RegionsAdapter.RegionViewHolder(view, mListener);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onClick(v,holder.getLayoutPosition());
}
});
return holder;
}
#Override
public void onBindViewHolder(RegionViewHolder holder, final int position){
holder.regionName.setText(mRegionList.get(position).getRegionName());
holder.regionSeason.setText(mRegionList.get(position).getSeason());
holder.regionAss.setText(mRegionList.get(position).getAssociation());
}
#Override
public int getItemCount() {
return mRegionList.size();
}
And this is the fragment that it is supposed to show the data base on:
public class RegionFragment extends Fragment {
private List<Region> mRegionList;
private RecyclerView mRecyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.region_fragment, container, false);
//whenever the activity is started, it reads data from database and stores it into
// local array list 'mRegionList'
final AppDatabase db = Room.databaseBuilder(getActivity().getApplicationContext(),
AppDatabase.class,"app_database").allowMainThreadQueries().build();
List<Region> regionList = db.getRegionDao().getAll();
// Initializing the RecyclerView
mRecyclerView = view.findViewById(R.id.region_rv);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
RegionsAdapter adapter = new RegionsAdapter(regionList, getActivity().
getApplicationContext(), R.id.region_layout, new RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
// Handling what happenes when a card is clicked
// TODO handling
}
});
mRecyclerView.setAdapter(adapter);
return view;
}
This is the AppDatabase Class:
#Database(entities = {Region.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract RegionDao getRegionDao();
private static AppDatabase sInstance;
static AppDatabase getDatabase(final Context context) {
if (sInstance == null) {
synchronized (AppDatabase.class){
if (sInstance == null) {
sInstance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
"database").addCallback(sRoomDatabaseCallback).build();
}
}
}
return sInstance;
}
private static RoomDatabase.Callback sRoomDatabaseCallback =
new RoomDatabase.Callback() {
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
new PopulateDbAsync(sInstance).execute();
}
};
And finally the AsyncClass to pre populate the database:
class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private final RegionDao mDao;
PopulateDbAsync(AppDatabase db) {
mDao = db.getRegionDao();
}
#Override
protected Void doInBackground(final Void... params) {
mDao.deleteAll();
Region region = new Region(0,"Europe","UEFA","2017/2018");
mDao.insert(region);
region = new Region(1, "Americas","CONCACAF","2017/2018");
mDao.insert(region);
region = new Region(2, "Asia","AFC","2017/2018");
mDao.insert(region);
region = new Region(3, "International","FIFA","2017/2018");
mDao.insert(region);
region = new Region(4, "Other","ConIFA","2017/2018");
mDao.insert(region);
return null;
}
if your id is PrimaryKey(autoGenerate = true), then don't set id in constructor.
update your onCreateView , you are use wrong database.
final AppDatabase db =AppDatabase.getDatabase(getActivity());
List<Region> regionList = db.getRegionDao().getAll();// here you have fire your query in background thread. you can search for that