Nullpointerexception on RecyclerView - nullpointerexception

All im trying to do is create a recyclerview inside of a tablayout i have tried setting up the adapter in the main activity as well as the fragment im using in the tablayout however either way im still getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{knightsrealms.managment_app/knightsrealms.managment_app.Dashboard}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
package knightsrealms.managment_app;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import java.util.ArrayList;
import java.util.Calendar;
public class Dashboard extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPageAdapter viewPagerAdapter;
ArrayList<knightsrealms.managment_app.Calendar> contacts = new ArrayList<knightsrealms.managment_app.Calendar>(5);
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
setSupportActionBar(toolbar);
final TabLayout.Tab messages = tabLayout.newTab();
final TabLayout.Tab dashboard = tabLayout.newTab();
messages.setText("Messages");
dashboard.setText("Dashboard");
tabLayout.addTab(dashboard, 0);
tabLayout.addTab(messages, 1);
tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
RecyclerView rvContacts = (RecyclerView)findViewById(R.id.rvcal);
contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
CalendarAdapter adapter = new CalendarAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard_menu, menu);
return true;
}
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
}
this is my adapter
package knightsrealms.managment_app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class CalendarAdapter extends RecyclerView.Adapter<CalendarAdapter.ViewHolder> {
// 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 static class ViewHolder extends RecyclerView.ViewHolder {
// Your holder should contain a member variable
// for any view that will be set as you render a row
public TextView nameTextView;
public Button messageButton;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ViewHolder(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);
nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
messageButton = (Button) itemView.findViewById(R.id.message_button);
}
}
private List<Calendar> mContacts;
// Pass in the contact array into the constructor
public CalendarAdapter(List<Calendar> contacts) {
mContacts = contacts;
}
// Usually involves inflating a layout from XML and returning the holder
#Override
public CalendarAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.recyclercell, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
// Involves populating data into the item through holder
#Override
public void onBindViewHolder(CalendarAdapter.ViewHolder viewHolder, int position) {
// Get the data model based on position
Calendar contact = mContacts.get(position);
// Set item views based on the data model
TextView textView = viewHolder.nameTextView;
textView.setText(contact.getName());
Button button = viewHolder.messageButton;
if (contact.isOnline()) {
button.setText("Message");
button.setEnabled(true);
}
else {
button.setText("Offline");
button.setEnabled(false);
}
}
// Return the total count of items
#Override
public int getItemCount() {
return mContacts.size();
}
}
This code is for the fragment which is inside the tablayout
<android.support.v7.widget.RecyclerView
android:id="#+id/rvcal"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
And this is the main activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_below="#+id/tool_bar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:tabIndicatorHeight="3dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tabs"
/>
</RelativeLayout>
any insight/help into this is greatly appreciated thank you!!

have you already try in :
tabLayout.setupWithViewPager(viewPager);
Well because recyclerView is in your fragment xml not in your activity xml, thus the recyclerView is return null.
Ok, So your code is almost done, but you need 2 more things:
first, is a class that extends FragmentPagerAdapter for your ViewPager, I don't know if your ViewPageAdapter class is already do that, but let's assume you're not yet done that.
second, is a fragment for your FragmentPagerAdapter.
Oke Lets start :
Create FragmentContacts for the FragmentPagerAdapter, in this fragment you should manage your RecyclerView and it's adapter not in the Activity.
public class FragmentContacts extends Fragment {
ArrayList<knightsrealms.managment_app.Calendar> contacts = new ArrayList<knightsrealms.managment_app.Calendar>(5);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = (View) inflater.inflate(R.layout.your_fragment_xml, container, false);
contacts.add(0, new knightsrealms.managment_app.Calendar("Number 1",true));
contacts.add(1, new knightsrealms.managment_app.Calendar("Number 2",true));
CalendarAdapter adapter = new CalendarAdapter(contacts);
RecyclerView rvContacts = (RecyclerView) rootView.findViewById(R.id.rvcal);
rvContacts.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
rvContacts.setAdapter(adapter);
return rootView;
}
}
Lastly, back in your Dashboard Activity, in onCreate, setUp your Viewpager :
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPagerAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0);
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new FragmentContacts();
if(position == 1) return new FragmentContacts();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Messages";
if(position == 1) return "Dashboard";
throw new IllegalStateException("Unexpected position " + position);
}
}

Related

Why doesn't my radioButton get checked or unchecked?

I followed a tutorial to check a single radioButton. I tried to change it so you can change multiple radioButtons.
I succeeded to get the value out of the arraylist and show it on the screen, but when I click on it doesn't change. Only the radioButton that is unchecked get checked. Can anyone help me with this.
public interface ItemClickListener {
//Create method
void onClick(String s);
}
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.AdapterView;
import android.widget.RadioButton;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//Initialize variable
RecyclerView recyclerView;
ItemClickListener itemClickListener;
MainAdapter adapter;
ArrayList<String> arrayList;
ArrayList<Boolean> arrayList_B;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Assign variable
recyclerView = findViewById(R.id.recycler_view);
fillArrayList();
//Initialize listener
itemClickListener = new ItemClickListener() {
#Override
public void onClick(String s) {
//Notify adapter
recyclerView.post(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
//Display toast
Toast.makeText(getApplicationContext(),
"Selected : " + s, Toast.LENGTH_SHORT).show();
}
};
//Set layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Initialize adapter
adapter = new MainAdapter(arrayList, arrayList_B, itemClickListener);
//Set adapter
recyclerView.setAdapter(adapter);
}
public void fillArrayList() {
//initialize array list
arrayList = new ArrayList<>();
arrayList_B = new ArrayList<>();
//Use for loop
for (int i = 0; i < 10; i++) {
//Add values in array list
arrayList.add("RB " + i);
arrayList_B.add(true);
}
arrayList_B.set(3,false);
}
}
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
//Initialize variable
ArrayList<String> arrayList;
ArrayList<Boolean> arrayList_B;
ItemClickListener itemClickListener;
int selectedPosition = -1;
//Create constructor
public MainAdapter(ArrayList<String> arrayList, ArrayList<Boolean> arrayList_B, ItemClickListener itemClickListener) {
this.arrayList = arrayList;
this.itemClickListener = itemClickListener;
this.arrayList_B = arrayList_B;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Initialize view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_main, parent, false);
//Pass holder view
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set text on radio button
holder.radioButton.setText(arrayList.get(position));
//Set true or false radio button
holder.radioButton.setChecked(arrayList_B.get(position));
//Set listener on radio button
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//When checked
//Update selected position
selectedPosition = holder.getAdapterPosition();
//if (arrayList_B.get(selectedPosition).equals(true)) {
//if (b == true) {
// arrayList_B.set(selectedPosition, false);
//}
//if (b == false) {
//
//}
arrayList_B.set(selectedPosition, b);
holder.radioButton.setChecked(arrayList_B.get(selectedPosition));
//Call listener
//Get RadioButton name.
itemClickListener.onClick(holder.radioButton.getText().toString());
//set array list radiobutton
}
});
}
#Override
public long getItemId(int position) {
//Pass position
return position;
}
#Override
public int getItemViewType(int position) {
//Pass position
return position;
}
#Override
public int getItemCount() {
//Pass total List size
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
radioButton = itemView.findViewById(R.id.radiobutton);
}
}
}
The Layout: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view"
tools:listitem="#layout/item_main"/>
</RelativeLayout>
The Layout: item_main.xml
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radiobutton"
android:padding="12dp"
android:textSize="18sp"
android:textColor="#android:color/darker_gray"/>

RecyclerView and Item Position and click on particular item

This is the interface of my application, my question is, if I click on "video lecture" then it should go to Video Lecture Activity and if i click on "Detail Notes" then it should go in Detail Notes Activity. Similarly, i want to do with all recyclerView items.
This is my Adapter code
package com.example.motionofknowledge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.motionofknowledge.databinding.ActivityMaterialsBinding;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class Materials extends AppCompatActivity {
ActivityMaterialsBinding binding;
FirebaseFirestore database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMaterialsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
String head = getIntent().getStringExtra("subName");
TextView textView = findViewById(R.id.headingMat);
textView.setText(new String(head));
database = FirebaseFirestore.getInstance();
ArrayList<MatModel> materials = new ArrayList<>();
MatAdapter adapter = new MatAdapter(this,materials);
String subId = getIntent().getStringExtra("subId");
database.collection("subjects")
.document(subId)
.collection("mat")
.orderBy("index")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
materials.clear();
for (DocumentSnapshot snapshot:value.getDocuments()){
MatModel model = snapshot.toObject(MatModel.class);
model.setMatId(snapshot.getId());
materials.add(model);
}
adapter.notifyDataSetChanged();
}
});
binding.matList.setLayoutManager(new GridLayoutManager(this,2));
binding.matList.setAdapter(adapter);
binding.matHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Materials.this,MainActivity.class);
startActivity(intent);
}
});
}
}
This is my adapter code
package com.example.motionofknowledge;
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 com.bumptech.glide.Glide;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MatAdapter extends RecyclerView.Adapter<MatAdapter.MatViewHolder>{
Context context;
ArrayList<MatModel> matModels;
public MatAdapter(Context context, ArrayList<MatModel> matModels){
this.context = context;
this.matModels = matModels;
}
#NonNull
#Override
public MatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_category,null);
return new MatViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MatViewHolder holder, int position) {
MatModel model = matModels.get(position);
holder.textView.setText(model.getMatName());
Glide.with(context)
.load(model.getMatImage())
.into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,Chapters.class);
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return matModels.size();
}
public class MatViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public MatViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.category);
}
}
}
You did not post your adapter code, but your activity code. Anyway: I understand that you have a recyclerView with different kind of items in it (Video Lecture, Detail Notes, and more). Depending on which item the user clicks, you want to do different things.
This is done by using the onBindViewHolder method in your MatAdapter. This method does not only bind the data to the UI layout, but it should also be used to bind a click listener to the UI layout.
If you have only a few items in your RecyclerView, you could use the getItem(position) method of your adapter to find out what specific item you are dealing with within onBindViewHolder. As soon as you know what kind of item the Adapter wants to bind, you can set the according click listener.
See this suggestion:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = null
if (model.type == VIDEO) {
intent = new Intent(context,Video.class);
} else if (model.type == DETAILS) {
intent = new Intent(context,Details.class);
} else {
...
}
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
model is the current MatModel that you want to bind.
model.type is any way to distinguish the different items. I do not know the details of the MatModel class, but you somehow need to be able to distinguish the different models, of course.

I added Recycler view in fragment, now I am trying to pass image to recycler view, but app is crashing with error msg on logcat

Error on logcat:
2021-02-18 00:36:44.712 11507-11507/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chitchat, PID: 11507
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.chitchat.RecycleAdapter.onBindViewHolder(RecycleAdapter.java:56)
at com.example.chitchat.RecycleAdapter.onBindViewHolder(RecycleAdapter.java:16)
//////////////////////code from fragment activity////////////////////
package com.example.chitchat;
import android.os.Bundle;
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 java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link homefragrent#newInstance} factory method to
* create an instance of this fragment.
*/
public class homefragrent extends Fragment {
private RecycleAdapter recycleAdapter;
private RecyclerView recyclerView;
// private RecyclerView.LayoutManager layoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public homefragrent() {
// Required empty public constructor
}
/**
* 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 homefragrent.
*/
// TODO: Rename and change types and number of parameters
public static homefragrent newInstance(String param1, String param2) {
homefragrent fragment = new homefragrent();
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.fragment_homefragrent, container, false);
recyclerView= (view).findViewById(R.id.recycler);
ArrayList<postmodel> exampleimgs = new ArrayList<>();
exampleimgs.add(new postmodel(R.drawable.oner,"post1"));
exampleimgs.add(new postmodel(R.drawable.twor,"post2"));
exampleimgs.add(new postmodel(R.drawable.threer,"post3"));
exampleimgs.add(new postmodel(R.drawable.fourr,"post4"));
exampleimgs.add(new postmodel(R.drawable.fiver,"post5"));
exampleimgs.add(new postmodel(R.drawable.sixr,"post6"));
exampleimgs.add(new postmodel(R.drawable.node,"post7"));
// layoutManager = new LinearLayoutManager(getActivity());
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recycleAdapter = new RecycleAdapter(exampleimgs);
recyclerView.setAdapter(recycleAdapter);
return view;
}
}
///////////////Recycle arapter//////////////////
package com.example.chitchat;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.RecycleViewHolder>{
Context context;
ArrayList<postmodel> imgsl;
public RecycleAdapter(ArrayList<postmodel> imgsl) {
this.context = context;
this.imgsl = imgsl;
}
public class RecycleViewHolder extends RecyclerView.ViewHolder{
TextView textView;
ImageView imageView;
public RecycleViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.textView);
imageView=itemView.findViewById(R.id.imageView);
}
}
#NonNull
#Override
public RecycleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.homefrgmentlayout,parent,false);
RecycleViewHolder recycleViewHolder = new RecycleViewHolder(view);
return recycleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecycleViewHolder holder, int position) {
postmodel currentposition = imgsl.get(position);
holder.imageView.setImageResource(currentposition.getImgs());
holder.textView.setText(currentposition.getComment());
}
#Override
public int getItemCount() {
return imgsl.size();
}
}
//////////////////////////////model class//////////////////////
package com.example.chitchat;
public class postmodel {
private int imgs;
private String comment;
public postmodel(int imgs, String comment) {
this.imgs = imgs;
this.comment = comment;
}
public int getImgs() {
return imgs;
}
public void setImgs(int imgs) {
this.imgs = imgs;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
I feel here it would be
//Pass context from Activity to the adapter
imageView.setImageResource(context.getResources.getDrawables.image)
In Activity
recycleAdapter = new RecycleAdapter(this,exampleimgs);
recyclerView.setAdapter(recycleAdapter);
In Adapter
public RecycleAdapter(Context context, ArrayList<postmodel> imgsl) {
this.context = context;
this.imgsl = imgsl;
}
and then the above line to set image

How can I include a recyclerView (contains a list of items) in one activity that has other views

I want to achieve something like below, my list data is coming from a restful server. Everything is working except that the list is empty.
I used the following;
* Recyclerview Adaptor
* Created a pojo for list items, logs show that that the data is coming through from the server except that the list is not populated
//TransactionsFragment
public class TransactionsFragment extends Fragment {
View rootView;
RecyclerView recyclerView;
String transaction_amount;
String transaction_date_created;
public String authToken;
public TransactionsFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_transactions_list, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = rootView.findViewById(R.id.rv_transactions);
recyclerView.setLayoutManager(linearLayoutManager);
TransactionListAdapter transactionListAdapter = new TransactionListAdapter(getContext(), getTransactions());
recyclerView.setAdapter(transactionListAdapter);
transactionListAdapter.notifyDataSetChanged();
return rootView;
}
private List<Transaction> getTransactions() {
List<Transaction> transactionList = new ArrayList<>();
/........
#Override
public void onNext(List<Transaction> transactions) {
Integer transactionSize = transactions.size();
for (int i =0;i<transactionSize;i++) {
transaction_amount = transactions.get(i).getAmount();
transaction_date_created = transactions.get(i).getDateCreated();
transactionList.add(new Transaction(transactions.get(i).getId(),null,transactions.get(i).getAmount(), transactions.get(i).getDateCreated(), transactions.get(i).getAccount()));
}
/// Data is shown here after running the app so it tells me that we are getting response from the server
Toast.makeText(getActivity(), "Transaction Date Created: " + transaction_date_created + "!", Toast.LENGTH_LONG).show();
}
#Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException) e;
int code = response.code();
String msg = response.message();
Toast.makeText(getActivity(), "Transaction Error message: " + msg + "!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onComplete() {
}
});
//...
return transactionList;
}
}
//..TransactionListAdapter
public class TransactionListAdapter extends RecyclerView.Adapter {
private List transactionList;
private Context mContext;
public TransactionListAdapter(Context context, List<Transaction> transactions) {
this.mContext = context;
this.transactionList = transactions;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_transactions_single, parent, false);
vh = new OriginalViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int i) {
if (holder instanceof TransactionListAdapter.OriginalViewHolder) {
TransactionListAdapter.OriginalViewHolder view = (TransactionListAdapter.OriginalViewHolder) holder;
Transaction transaction = transactionList.get(i);
view.tvTransactionAmount.setText(transaction.getAmount());
view.tvTransactionDateCreated.setText(transaction.getDateCreated());
}
}
#Override
public int getItemCount() {
return transactionList.size();
}
public class OriginalViewHolder extends RecyclerView.ViewHolder{
ImageView imgTransactionType;
TextView tvTransactionName, tvTransactionAmount, tvTransactionDateCreated, tvDefaultCurrency, getTvTransactionUSD;
public OriginalViewHolder(View itemView) {
super(itemView);
tvTransactionDateCreated = itemView.findViewById(R.id.tv_transaction_date_created);
tvTransactionAmount = itemView.findViewById(R.id.tv_transaction_amount);
}
}
}
//..MainActivity
public class MainActivity extends AppCompatActivity implements
View parent_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkConnection();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
setContentView(R.layout.activity_home);
initiateViews();
Fragment transFragment = new TransactionsFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.transactions_frame_container, transFragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void initiateViews() {
parent_view = (CoordinatorLayout)findViewById(R.id.home_container);
home_container_id = R.id.frame_container;
}
private void loadFragment(Fragment fragment, Integer container_id) {
// create a FragmentManager
FragmentManager fm = getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(container_id, fragment);
fragmentTransaction.commit(); // save the changes
}
}
//..fragment_transactions_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_10" />
<View
android:layout_width="0dp"
android:layout_height="#dimen/spacing_middle" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv_transactions"
android:scrollbars="vertical"
android:scrollingCache="true"/>
</LinearLayout>

Add Recyclerview in RecyclerViewPager

I added a Recyclerview in one item of RecyclerViewPager(https://github.com/lsjwzh/RecyclerViewPager).
And I want to scroll the RecyclerView when I touch on it.
I have tried :
View.OnTouchListener listener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
mRecyclerViewPager.requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mRecyclerViewPager.requestDisallowInterceptTouchEvent(false);
break;
}
return false;
}
};
mRecyclerView.setOnTouchListener(listener);
But I can only scroll the RecyclerView sometimes.
I think it can be sloved by implementing NestedScrollingParent in RecyclerViewPager or changing onTouchEvent in RecyclerViewPager .But I'm not familiar with them.
I followed the steps to configure and create the simple example using the Github documentation.
Main Activity XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.stackoverflow.recyclerviewstack.MainActivity">
<com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="1dp"
android:paddingRight="1dp"
app:rvp_triggerOffset="0.1"
app:rvp_singlePageFling="true"
android:clipToPadding="false"
/>
</RelativeLayout>
Main Activiy class
package com.stackoverflow.recyclerviewstack;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;
public class MainActivity extends AppCompatActivity {
RecyclerAdapter mAdapter;
RecyclerViewPager mRecycler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecycler = (RecyclerViewPager) findViewById(R.id.list);
// setLayoutManager like normal RecyclerView, you do not need to change any thing.
LinearLayoutManager layout = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecycler.setLayoutManager(layout);
//set adapter
//You just need to implements ViewPageAdapter by yourself like a normal RecyclerView.Adpater.
mAdapter = new RecyclerAdapter(ItemListGenerator.generateCollection(15, "OutItem "));
mRecycler.setAdapter(mAdapter);
}
}
RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
List<String> collection;
public RecyclerAdapter(List<String> collection) {
this.collection = collection;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
RecyclerView mInnerRecycler;
public ViewHolder(View view) {
super(view);
item = (TextView) view.findViewById(R.id.title);
mInnerRecycler = (RecyclerView) view.findViewById(R.id.innerRecycler);
LinearLayoutManager layout = new LinearLayoutManager(view.getContext(),
LinearLayoutManager.HORIZONTAL, false);
mInnerRecycler.setLayoutManager(layout);
mInnerRecycler.setAdapter(new InnerAdapter());
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.outer_collection, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position < 0 || position > getItemCount()) return;
String itemString = collection.get(position);
holder.item.setText(itemString);
}
#Override
public int getItemCount() {
return collection.size();
}
}
the layout use by RecyclerViewPager to create ViewHolder
The ViewHolder use the layout outer_collection:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip"
android:layout_margin="2dip"
android:background="#color/colorPrimary"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/innerRecycler"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
The InnerAdapter
public class InnerAdapter extends RecyclerView.Adapter<InnerAdapter.ViewHolder> {
List<String> collection;
public InnerAdapter() {
this.collection = ItemListGenerator.generateCollection(15, "Inner ");
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
item = (TextView) itemView.findViewById(R.id.item);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.simple_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position < 0 || position > getItemCount()) return;
holder.item.setText(collection.get(position));
}
#Override
public int getItemCount() {
return collection.size();
}
}
Tip
For the RecyclerViewPager I used this orientation:
LinearLayoutManager layout = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
And for the RecyclerView inside this one:
LinearLayoutManager layout = new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false);
If you use VERTICAL in the PagerView you can navigate in the horizontal collection or change to HORIZONTAL the PagerView orientation and you can scroll your inside items in the VERTICAL orientation.
You have to evaluate how do you want to use it. I hope this code help with your problem and also to rethink your design. Maybe is not a good practice or UX use the same orientation for both containers. I am not a UX expert.
I will like to be more helpful.