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();
}
Related
Howdy, I'm working on a project and I'm running into some issues. Namely, I have two fragments, each with their own adapter as both fragments are meant to be able to swipe horizontally. A photo should be attached of the layout I have for further clarity. I would like to be able to tap the bottom fragment, which when I tap a place on the top fragment, the image I tapped or "Structure" will be placed down. However, what I can't figure out is how to smoothly transfer this data and if I were to do it through the activity, how do I do it as the activity has already run through all its code. Could somebody please help, it would be greatly appreciated.
Main Activity
public class MainMap extends AppCompatActivity
{
MapData data = MapData.get();
StructureData structure = StructureData.get();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map);
FragmentManager frag = getSupportFragmentManager(); //To manage the map fragment
MapCellFragment rv = (MapCellFragment) frag.findFragmentById(R.id.map);
FragmentManager selectionFrag = getSupportFragmentManager(); //To manage the selection fragment
SelectionCellFragment cf = (SelectionCellFragment) selectionFrag.findFragmentById(R.id.bar);
if (rv == null)
{
rv = new MapCellFragment(data);
frag.beginTransaction().add(R.id.map, rv).commit();
}
if (cf == null)
{
cf = new SelectionCellFragment(structure);
selectionFrag.beginTransaction().add(R.id.bar, cf).commit();
}
}
Map Fragment
public MapData data;
public MapCellFragment() {
// Required empty public constructor
}
public MapCellFragment(MapData data)
{
this.data = data;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment gridCellFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapCellFragment newInstance(String param1, String param2) {
MapCellFragment fragment = new MapCellFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.map_fragment, container, false);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
rv.setLayoutManager(new GridLayoutManager(getActivity(), MapData.HEIGHT, GridLayoutManager.HORIZONTAL,false));
MapAdapter myAdapter = new MapAdapter(data);
rv.setAdapter(myAdapter);
return view;
}
Bottom Bar Fragment
This was essentially a copy and paste of the other fragment, just changing the data which goes in and the XML it's attached to.
Map Adapter
package com.example.map;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>
{
MapData data;
public MapAdapter(MapData data)
{
this.data = data;
}
#NonNull
#Override
public MapViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.grid_cells,parent,false);
//Resizes the images within the grid cells xml file
int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
ViewGroup.LayoutParams lp = view.getLayoutParams();
lp.width = size;
lp.height = size;
MapViewHolder myViewHolder = new MapViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MapViewHolder holder, int position)
{
int row = position % MapData.HEIGHT;
int col = position / MapData.HEIGHT;
MapElement ele = data.get(row, col);
holder.ne.setImageResource(ele.getNorthEast());
holder.nw.setImageResource(ele.getNorthWest());
holder.se.setImageResource(ele.getSouthEast());
holder.sw.setImageResource(ele.getSouthWest());
if(ele.getStructure() != null)
{
holder.mapStruct.setImageResource(ele.getStructure().getDrawableId());
}
}
#Override
public int getItemCount()
{
return 300;
}
}
Map View Holder
package com.example.map;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Objects;
public class MapViewHolder extends RecyclerView.ViewHolder {
ImageView nw;
ImageView ne;
ImageView sw;
ImageView se;
ImageView mapStruct;
public MapViewHolder(#NonNull View itemView)
{
super(itemView);
nw = itemView.findViewById(R.id.northWest);
ne = itemView.findViewById(R.id.northEast);
sw = itemView.findViewById(R.id.southWest);
se = itemView.findViewById(R.id.southEast);
mapStruct = itemView.findViewById(R.id.structure);
}
}
Bar Adapter
package com.example.map;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SelectionAdapter extends RecyclerView.Adapter<SelectionViewHolder>
{
StructureData data;
public SelectionAdapter(StructureData data)
{
this.data = data;
}
#NonNull
#Override
public SelectionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.list_selection,parent,false);
SelectionViewHolder myViewHolder = new SelectionViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull SelectionViewHolder holder, int position)
{
Structure s = data.get(position);
holder.structure.setImageResource(s.getDrawableId());
holder.label.setText(s.getLabel());
holder.bind(s);
}
#Override
public int getItemCount()
{
return data.size();
}
}
Bar ViewHolder
package com.example.map;
import android.annotation.SuppressLint;
import android.util.Log;
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 java.util.Objects;
public class SelectionViewHolder extends RecyclerView.ViewHolder
{
Structure selectObject;
ImageView structure;
TextView label;
public SelectionViewHolder(#NonNull View itemView)
{
super(itemView);
structure = itemView.findViewById(R.id.image);
label = itemView.findViewById(R.id.label);
structure.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SelectionCellFragment.selectedData = selectObject;
}
});
}
public void bind(Structure s)
{
selectObject = s;
}
//Maybe, I need to place this bind function in MapViewHolder as well
//When I press on the button, I must share the information over to the Map fragment
//Then the new information will form a ImageView on the big one
}
You could use ViewModel to solve your use-case. You could have something like SelectedStructureViewModel that will be set in the SelectionCellFragment when the user taps to select the structure. While the MapCellFragment can observe this SelectedStructureViewModel to be notified whenever the user selects the structure. You can then query it when user taps a place on the Map.
I am absolute beginner for this, I'm sorry if this such a dumb mistakes.
so, I created fragment in which i have got recyclerView, but my recycler view is empty, i saw that my context is empty, and i think, that it can be the reason of this, i try to use getActivity
here is code of my fragment
package com.example.pocketcinema;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class SearchFragment extends Fragment implements RecyclerViewInterface {
private RecyclerView recyclerView;
RecyclerViewInterface rci;
MyAdapter myAdapter;
public List<String> nameOfFilm, youTubeUrl, photoUrl, descriptionToFilm, category;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
recyclerView = inflater.inflate(R.layout.fragment_search, container,
false).findViewById(R.id.filmsList);
rci = this;
nameOfFilm = new ArrayList<>();
youTubeUrl = new ArrayList<>();
photoUrl = new ArrayList<>();
descriptionToFilm = new ArrayList<>();
category = new ArrayList<>();
loadFilmsFromDB();
return inflater.inflate(R.layout.fragment_search, container, false);
}
private void loadFilmsFromDB() {
Context context = requireContext();
db.collection("films").get().addOnCompleteListener(new
OnCompleteListener<QuerySnapshot>()
{
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (QueryDocumentSnapshot document : task.getResult()) {
nameOfFilm.add(document.get("nameOfFilm").toString());
descriptionToFilm.add(document.get("descriptionToFilm").toString());
photoUrl.add(document.get("imageUrl").toString());
youTubeUrl.add(document.get("videoURL").toString());
category.add(document.get("category").toString());
myAdapter = new MyAdapter(context, nameOfFilm, descriptionToFilm,
photoUrl, youTubeUrl,
rci, category);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
}
}
});
}
here is screenshot with debuger, you can see that context = null
context = null
here you can see that i set layout for recyclerView
with logcat
here is Adapter
package com.example.pocketcinema;
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.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context ct;
List<String> name, description, image, video, category;
private final RecyclerViewInterface recyclerViewInterface;
public MyAdapter(Context ct, List<String> nameOfFilm, List<String>
descriptionOfFilm, List<String> imageUrl, List<String> videoUrl,
RecyclerViewInterface rci,List<String> category) {
name = nameOfFilm;
description = descriptionOfFilm;
image = imageUrl;
video = videoUrl;
this.ct = ct;
recyclerViewInterface = rci;
this.category = category;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(ct);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view, recyclerViewInterface);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int
position) {
holder.nameFilm.setText(name.get(position));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ct, PlayerActivity.class);
}
});
Picasso.get().load(image.get(position)).into(holder.image2);
}
#Override
public int getItemCount() {
return image.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView nameFilm;
ImageView image2;
CardView cardView;
public MyViewHolder(#NonNull View itemView, RecyclerViewInterface
recyclerViewInterface) {
super(itemView);
nameFilm = itemView.findViewById(R.id.nameTV);
image2 = itemView.findViewById(R.id.imageView2);
cardView = itemView.findViewById(R.id.cardView);
itemView.findViewById(R.id.sectionOFRecyclerView).setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recyclerViewInterface != null) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
recyclerViewInterface.onItemClick(pos);
}
}
}
});
}
}
}
myAdapter isn't null
You are trying to create an instance of activity as global variable. That means the context has not been generated yet.
Basically you can just use requireContext() method of Fragment class. This will provide you the context.
As I have mentioned in comment, you need to update your onCreateView method as below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_search, container, false);
}
Then, you need to initialize your view and other stuff on onViewCreated method. You can update that method like this:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.filmsList);
textView = view.findViewById(R.id.test);
rci = this;
nameOfFilm = new ArrayList<>();
youTubeUrl = new ArrayList<>();
photoUrl = new ArrayList<>();
descriptionToFilm = new ArrayList<>();
category = new ArrayList<>();
loadFilmsFromDB();
}
Notes
You don't have to send many string parameters to your adapter. It is better to create a Model class for that item, and send the list of that item. So, model classes will have all the data you need, and you can use them from that model. This will give you better coding style and will let you manage your data easier.
To communicate with your XML layout, you can use ViewBinding or DataBinding for that. This will also help you to use your view elements without creating variables for each of them.
I developed a vocabulary app where users can select their favorite words to a favourite section. I have two problems.
First, my code looks okay but when I choose a word from the list it doesn't show in the favorite section immediately. However, when I re-open the application it appears there.
The second problem is with the words which repeat in list with any run.
Here's my code :
Adapter list
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterList extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterList(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.list.get(position).getWord());
String img = MainActivity.list.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "list");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.list.size();
}
}
Adapter favorite
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
When you update your data set call adapater.notifyChange();
Please am having issue with this null error message java.lang.NullPointerException (no error message). I really need assistance on how and where to add the appropriate code so that the application would not crash. Here is the JAVA file that i am having issues with. I am trying to create a recycler view and jpg images from my drawable folder
HorizontalListAdapter.java
import android.app.Activity;
import android.graphics.Picture;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class HorizontalListAdapter extends RecyclerView.Adapter<HorizontalListAdapter.ViewHolder>
{
private Activity activity;
int[] images= {R.drawable.vb1,R.drawable.pota,R.drawable.vb1,
R.drawable.pota,R.drawable.vb1,R.drawable.download1,R.drawable.pota};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
public HorizontalListAdapter(Activity activity)
{
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_horizontal_list, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HorizontalListAdapter.ViewHolder viewHolder, final int position) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private ImageView imageView;
private TextView txtview;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.imageview);
txtview = (TextView) view.findViewById(R.id.txtview);
linearLayout = (LinearLayout) view.findViewById(R.id.layout);
}
}
}
The second java class VerticalListAdapter.java
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.ViewHolder> {
private Activity activity;
public VerticalListAdapter(Activity activity) {
this.activity = activity;
}
int[] images= {R.drawable.images,R.drawable.images,R.drawable.images,
R.drawable.images,R.drawable.images,R.drawable.images,R.drawable.images};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
String[] cost={"Rs 200","Rs 300","Rs 150","R 320","Rs 450","Rs 120","Rs 380"};
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_recycler_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// if ((position + 1) % 2 == 0) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.txtCost.setText("Cost Per Person "+cost[position]);
// } else {
// viewHolder.imageView.setImageResource(R.drawable.awadhi_lucknow_biryani);
//}
viewHolder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView txtview;
private TextView txtCost;
private RelativeLayout container;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.image);
txtview = (TextView) view.findViewById(R.id.text);
txtCost= (TextView) view.findViewById(R.id.textView);
container = (RelativeLayout) view.findViewById(R.id.container);
}
}
}
Please i need assistance with this i guess it is the int[]images causing the error i may be wrong please correct me with the right code i would use to replace and make the code work.
changeimageview accessibility form private to any other modifier & try again
I have implemented RecyclerView in my app and have setup a onClickListener on Recycler View. The text fields are passing successfully, however I also have a image in the recyclerview, which is being brought through picasso. So I try to retrieve the image url which is stored in another class, but I'm getting a empty value.
The code is:
package xyz.xyz;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class FlatSearchCardAdapter extends RecyclerView.Adapter<FlatSearchCardAdapter.ViewHolder> {
private Context context;
private ImageLoader imageLoader;
List<FlatCardItemReturn> flatlistCard;
public FlatSearchCardAdapter(List<FlatCardItemReturn> flatlistCard, Context context){
super();
//Getting all the superheroes
this.flatlistCard = flatlistCard;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.flatrenter_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FlatCardItemReturn flatcarditemreturn = flatlistCard.get(position);
Picasso.with(context).load(flatcarditemreturn.getImageUrl()).placeholder(R.drawable.loadingpicasso).error(R.drawable.errorpicasso).resize(100, 100).into(holder.imageView);
holder.textViewId.setText(flatcarditemreturn.getId());
holder.textViewType.setText(flatcarditemreturn.getType());
holder.textViewFurnishing.setText(flatcarditemreturn.getFurnishing());
holder.textViewArea.setText(flatcarditemreturn.getArea());
holder.textViewPrice.setText(flatcarditemreturn.getPrice());
holder.textViewNumberofrooms.setText(flatcarditemreturn.getNumberofrooms());
}
#Override
public int getItemCount() {
return flatlistCard.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView textViewType;
public TextView textViewPrice;
public TextView textViewFurnishing;
public TextView textViewArea;
public TextView textViewNumberofrooms;
public TextView textViewId;
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
public ViewHolder(View itemView) {
super(itemView);
textViewId = (TextView) itemView.findViewById(R.id.id);
imageView = (ImageView) itemView.findViewById(R.id.flatphoto);
textViewType = (TextView) itemView.findViewById(R.id.type);
textViewFurnishing = (TextView) itemView.findViewById(R.id.furnishing);
textViewArea = (TextView) itemView.findViewById(R.id.area);
textViewPrice = (TextView) itemView.findViewById(R.id.price);
textViewNumberofrooms = (TextView) itemView.findViewById(R.id.numberofrooms);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), flatrenterpostview.class);
i.putExtra("idvalue", textViewId.getText().toString());
i.putExtra("typevalue", textViewType.getText().toString());
i.putExtra("furnishingvalue", textViewFurnishing.getText().toString());
i.putExtra("areavalue", textViewArea.getText().toString());
i.putExtra("pricevalue", textViewPrice.getText().toString());
i.putExtra("numberofroomsvalue", textViewNumberofrooms.getText().toString());
i.putExtra("imageurl", flatcarditemreturn.getImageUrl());
v.getContext().startActivity(i);
}
});
}
}
}
I'm pretty confused on how to set the position in that, so as to get the currect value. Will be grateful if anyone can help me out.
Just to make it clear, i.putExtra("imageurl", flatcarditemreturn.getImageUrl()); is giving nothing. I expect the url stored in my class. The url is stored perfectly, I checked.
Just to make it clear, i.putExtra("imageurl", flatcarditemreturn.getImageUrl()); is giving nothing. I expect the url stored in my class
Then why do you create a new FlatCardItemReturn in your ViewHolder? This line:
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
You'll want to set the correct data item to the ViewHolder, rather that instantiating a new 'empty' one. You can easily accomplish this by adding a method to the ViewHolder:
public void setData(FlatCardItemReturn item) {
flatcarditemreturn = item;
}
Now, just call this from onBindViewHolder():
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FlatCardItemReturn flatcarditemreturn = flatlistCard.get(position);
// other stuff omitted
holder.setData(flatcarditemreturn);
}
You can now also change:
public FlatCardItemReturn flatcarditemreturn = new FlatCardItemReturn();
into:
public FlatCardItemReturn flatcarditemreturn;