RecycleView doesnt show any items - java

This is the first time I'm going for a recycled view, I added the adaptor class and all, no errors in the code but nothing shows up. I did everything according to the first answer in this post Simple Android RecyclerView example but still there is something that I'm doing wrong and I don't know where to look for it. In the Run log I found this error
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList
but I tried fixing it with what I found online but still it didn't work
package com.mircea.bookapp;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class BookActivity extends AppCompatActivity implements BookListViewAdapter.ItemClickListener {
BookListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
//Hardcoded books
List<Book> books = new ArrayList<>();
books.add(new Book(" In Search of Lost Time", "Marcel Proust", 1913, "modernist"));
books.add(new Book(" In Search of Lost Time", "Marcel Proust", 1913, "modernist"));
books.add(new Book(" In Search of Lost Time", "Marcel Proust", 1913, "modernist"));
books.add(new Book(" In Search of Lost Time", "Marcel Proust", 1913, "modernist"));
books.add(new Book(" In Search of Lost Time", "Marcel Proust", 1913, "modernist"));
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.booklist);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new BookListViewAdapter(this, books);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
What am I doing wrong? Also here is the code for the BookListViewAdapter class
package com.mircea.bookapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class BookListViewAdapter extends RecyclerView.Adapter<BookListViewAdapter.ViewHolder> {
private List<Book> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
BookListViewAdapter(Context context, List<Book> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull BookListViewAdapter.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return mData.size();
}
// convenience method for getting data at click position
Book getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.bookTitle);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}

You need to setText in onBindViewHolder
#Override
public void onBindViewHolder(#NonNull BookListViewAdapter.ViewHolder holder, int position) {
holder. myTextView.setText()//the text you want
}

I think the problem is that you forgot to add your ArrayList. Try adding it with your RecyclerView setup code.
RecyclerView recyclerView = findViewById(R.id.booklist);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Add ArrayList here
adapter = new BookListViewAdapter(this, books);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);

Related

I am trying to reverse my recyclerview items but neither setReverseLayout nor Collection.reverse() works

I have an app trying to show its items from the latest item added to earlier ones in a grid view with GridLayoutManager, getting the items from firebase database, setReverseLayout works but when the items are not uniform or items total is an odd number, it leaves a vacant space for on item at the top like it omitted an item but it didnt, i tried using collections.reverse but it didnt really arrange the items from latest items, more like shuffled it and i still have that gap problem at the top. There is no error message, the app runs fine but its not displaying items the desired way.
Here is a screenshot of the problem with both methods I tried
Here is my recycler adapter code
package com.example.twelve.Adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.twelve.HomeActivity;
import com.example.twelve.Model.HomeProducts;
import com.example.twelve.Products_Page_Activity;
import com.example.twelve.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
List<HomeProducts> lstproducts = new ArrayList<>();
Context ncontext;
public RecyclerAdapter(List<HomeProducts> lstproducts, Context ncontext) {
this.lstproducts = lstproducts;
this.ncontext = ncontext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(ncontext).inflate(R.layout.home_product_items, parent, false));
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.cardview_pname.setText(lstproducts.get(position).getPname());
holder.cardview_category.setText(lstproducts.get(position).getCategory());
holder.cardview_price.setText(lstproducts.get(position).getPrice());
Picasso.get().load(lstproducts.get(position).getImageurllist().get(0)).into(holder.cardview_image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Products_Page_Activity.class);
intent.putExtra("pid", lstproducts.get(position).getPid());
intent.putExtra("prev_activity", "Home");
view.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return lstproducts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView cardview_image;
public TextView cardview_pname, cardview_category, cardview_price;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cardview_image = itemView.findViewById(R.id.rec_imgview);
cardview_pname = itemView.findViewById(R.id.rec_textviewname);
cardview_category = itemView.findViewById(R.id.rec_textviewcategory);
cardview_price = itemView.findViewById(R.id.rec_textprice);
}
}
}
Code to add products to the adapter
//Products are added in a list and passed to the adapter
DatabaseReference pref = FirebaseDatabase.getInstance().getReference("HomeProducts");
pref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
HomeProducts Hproducts = dataSnapshot.getValue(HomeProducts.class);
listtems.add(Hproducts);
Collections.reverse(listtems);
}
rcyAdapter = new RecyclerAdapter(listtems, HomeActivity.this);
rcyAdapter.notifyDataSetChanged();
recyclerView.setAdapter(rcyAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
try to get Collections.reverse(listtems); out of the for loop .. just after its end brace to complete getting all the items of the collection first and then reverse it
you should use setStackFromEnd :
GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setStackFromEnd(true);

Issue with the adapter and RecyclerView

I am making an app to upload photos and show them in a gallery.
When I run my app it doesn't load the photos from firebase database. It gives me the error:
No adapter attached; skipping layout
I tried many solutions but all failed.
This is the activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
and this is the adapter:
package com.example.android.shoftoh1;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.shoftoh1.R;
import com.example.android.shoftoh1.Upload;
import com.squareup.picasso.Picasso;
import java.util.List;
// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
static class ImageViewHolder extends RecyclerView.ViewHolder {
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView textViewName;
ImageView imageView;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
ImageViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
Appreciate your help.
Try making this ImageViewHolder public
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public class ImageViewHolder extends RecyclerView.ViewHolder {
// Your holder should contain a member variable
// for any view that will be set as you render a row
public TextView textViewName;
public ImageView imageView;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ImageViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
First of all, try to attach the adapter with empty list then call notifyDataSetChanged() on updating the list as :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
// attach the adapter with the empty list
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
//now that mUploads has been updated call notifyDataSetChanged().
//Also, if you know the position that was inserted you can
//use other variant such as notifyItemInserted().
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I suggest that you try to:
Move the adapter from the Firebase function to the rows that
define the Recycler View
Then update the list containing the data from Firebase (this can be the same list)
Finally, update the adapter that was made.
Good luck,
Well done!

error: cannot find symbol variable itemsAdapter

I'm following a tutorial and I can't get my project to successfully run. I keep getting the error: cannot find symbol variable itemsAdapter, even though my class is in the same folder. Any ideas? Thank you
MainActivity.java
itemsAdapter.java
MainActivity.java:
package com.example.simpletodo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<String> items;
Button btnAdd;
EditText etItem;
RecyclerView rvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = findViewById(R.id.btnAdd);
etItem = findViewById(R.id.etItem);
rvItems = findViewById(R.id.rvItems);
items = new ArrayList<>();
items.add("Buy milk");
items.add("Go to the gym");
items.add("Email Autumn");
itemsAdapter ItemsAdapter;
ItemsAdapter = new itemsAdapter(items);
rvItems.setAdapter(itemsAdapter);
rvItems.setLayoutManager(new LinearLayoutManager(this));
}
}
ItemsAdapter.java:
package com.example.simpletodo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class itemsAdapter extends
RecyclerView.Adapter<itemsAdapter.ViewHolder>{
List<String> items;
public itemsAdapter(List<String> items) {
this.items = items;
}
// #NonNull
#Override
// creates each view
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// Use layout inflator to inflate a view
View todoView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
// wrap it inside a View Holder and return it
return new ViewHolder(todoView);
}
// responsible for binding data to a particular view holder
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Grab the item at the position
String item = items.get(position);
// Bind the item into specified view holder
holder.bind(item);
}
// the # of items available in the data
#Override
public int getItemCount() {
return 0;
}
// Container to provide easy access to views that represent each row of the list
class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
// Update the view inside of the view holder with this data
public void bind(String item) {
}
}
In line 41 of MainActivity.java itemsAdapter needs to be ItemsAdapter
PS: Your naming standard for itemsAdapter is reversed from the convention. The class should be named ItemsAdapter and the variable/instance should be itemsAdapter

Android: RecyclerView.SetAdapter causes an application crash with no obvious error

We have been working on implementing a RecyclerView in our project for a while now, and although the backend seems to work just fine, as soon as I call the recyclerView.setAdapter it causes the program to crash. I have spent several hours poring over this program, and nothing yet, although I have suspicions that the answer lies in the adapter. Can anyone shed some light on this?
Create and set adapter:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView = findViewById(R.id.navRV);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(mLayoutManager);
Date todaysDate = new Date(System.currentTimeMillis());
AnnouncementList.add("Test Announcement 1", "This is some random text in the body" +
". It really needs to show up correctly!!", todaysDate);
mAdapter = new TwitterAdapter(mContext);
mRecyclerView.setAdapter(mAdapter);
And this is the adapter:
package com.company.application;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Twitter Adapter:
* This adapter is the interface between the data and the view
*/
public class TwitterAdapter extends RecyclerView.Adapter<TwitterAdapter.ViewHolder> {
//Use this as the tag for logging in this activity
final private String LOGTAG = "TWITTER_ADAPTER";
private Context mContext;
public TwitterAdapter(Context mContext) {
this.mContext = mContext;
}
#NonNull
#Override
public TwitterAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TwitterAdapter.ViewHolder holder, int position) {
//Set the text and the title
holder.textViewBody.setText((String)AnnouncementList.getList().get(position).getBody());
holder.textViewTitle.setText((String)AnnouncementList.getList().get(position).getTitle());
//If we have an image, insert it so we can draw it
if(AnnouncementList.getList().get(position).getImage() != null)
holder.imageView.setImageDrawable((Drawable)AnnouncementList.getList().get(position).getImage());
else
holder.imageView.setImageDrawable(null);
}
#Override
public int getItemCount() {
Log.d(LOGTAG, "getItemCount returns " + AnnouncementList.size());
return AnnouncementList.size();
}
/**
* Holds the view so that the RecyclerView can process it
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public RelativeLayout mRelativeLayout;
ImageView imageView;
TextView textViewTitle, textViewBody, textViewDate;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
textViewBody = itemView.findViewById(R.id.textViewBody);
// textViewDate = itemView.findViewById(R.id.textViewDate);
}
}
}
You need to pass the the arraylist to adapter like this
mAdapter = new TwitterAdapter(mContext, AnnouncementList);
Then in the adapter change the constructor like this
private Context mContext;
private ArrayList<ModelClass> mAnnouncementList = new ArrayList();
public TwitterAdapter(Context mContext,ArrayList<ModelClass> mAnnouncementList) {
this.mContext = mContext;
this.mAnnouncementList= mAnnouncementList;
}
and then access variables like this
holder.textViewBody.setText(mAnnouncementList.getList().get(position).getBody());
holder.textViewTitle.setText(mAnnouncementList.getList().get(position).getTitle());
dont forget to return the size like below
#Override
public int getItemCount() {
Log.d(LOGTAG, "getItemCount returns " + mAnnouncementList.size());
return mAnnouncementList.size();
}

Android Studio Radio button save state in listview fetched from sqlite

So i have an application where i fetched some poll from an sqlite db and used them in listview and now i tried to add a radio button but when i hit a button back that i created it doesn't save the choice i did from the radio button.
i open the app and...
i choose the second thing
but when i go back and in again the first is selected
here is my listAdapter.java
package com.hfad.myapp.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
import com.hfad.myapp.R;
import com.hfad.myapp.model.Cases;
import java.util.List;
public class ListCases extends BaseAdapter {
private Context mContext;
private List<Cases> mCasesList;
public ListCases(Context mContext, List<Cases> mCasesList) {
this.mContext = mContext;
this.mCasesList = mCasesList;
}
int pose = 0;
#Override
public int getCount() {
return mCasesList.size();
}
#Override
public Object getItem(int position) {
return mCasesList.get(position);
}
#Override
public long getItemId(int position) {
return mCasesList.get(position).getID();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_case_name);
TextView tvSize = (TextView)v.findViewById(R.id.tv_case_size);
TextView tvMsize = (TextView)v.findViewById(R.id.tv_case_msize);
RadioButton radioButton = (RadioButton)v.findViewById(R.id.radioButton);
radioButton.setChecked(position == pose);
radioButton.setTag(position);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pose = (Integer)view.getTag();
notifyDataSetChanged();
}
});
tvName.setText(mCasesList.get(position).getBrand());
tvSize.setText(mCasesList.get(position).getSize());
tvMsize.setText(mCasesList.get(position).getMsize());
return v;
}
}
i remind you that i did a database connection with an external database
it's really frustrating i couldn't find something similar and i can't solve this please help.
p.s. for any mistakes...i am really new in java and android studio in general.

Categories