Attempt to invoke virtual method null object reference - nullpointerexception

Main Activty:
TextView tvDescription;
ArrayList<String> descriptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDescription = (TextView)findViewById(R.id.tvDescription);
descriptions = new ArrayList<>();
descriptions.add("Description for item 1");
descriptions.add("Description for item 2");
descriptions.add("Description for item 3");
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(descriptions.get(index));
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/listFrag"
android:name="com.example.fragmentsvideo2018.ListFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_list" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/detailFrag"
android:name="com.example.fragmentsvideo2018.DetailFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#layout/fragment_detail" />
</LinearLayout>
ListFrag:
ItemSelected activity;
public interface ItemSelected
{
void onItemSelected (int index);
}
public ListFrag() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity = (ItemSelected) context;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> data = new ArrayList<String>();
data.add("1.This is item 1");
data.add("2.This is item 2");
data.add("3.This is item 3");
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data));
activity.onItemSelected(0);
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
activity.onItemSelected(position);
}
}
fragment_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".ListFrag">
<ListView
android:id="#+id/lvLIst"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Detail Frag:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
fragment_deal.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#color/design_default_color_primary"
android:orientation="vertical"
tools:context=".DetailFrag">
<TextView
android:id="#+id/tvDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="#string/textview"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
Error:
2021-09-11 16:27:03.357 29251-29251/com.example.fragmentsvideo2018 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fragmentsvideo2018, PID: 29251
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.fragmentsvideo2018.MainActivity.onItemSelected(MainActivity.java:30)
at com.example.fragmentsvideo2018.ListFrag.onActivityCreated(ListFrag.java:52)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2996)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:580)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:285)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I tried to search in this site and other but I didn't find the solution.
Maybe I'm doing something wrong because I'm only a beginner.
Please help me!!

As far as i can tell from the code you provided, the issue lies in the xml files. You try to get the TextView via findViewById() from within ActivityMain.java, but the TextView is declared in fragment_deal.xlm. As far as i know findViewById only finds components declared in the xml file associated with the java file calling.

Related

How to implement RecyclerView on a FrameLayout?

I am learning RecyclerView and stuck in activity. I have a bottomNavigationView and a frame layout above the bottomNavigationView I want to show a RecyclerView on that FrameLayout. How can I do that?
There is no error in my program and i don't know why its not showing the RecyclerView.
This is the 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"
tools:context=".Bottom_nav">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottomnavid"
/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomnavid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_nav"
/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#FFEB3B"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/live_matchrecyclerid"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
android:padding="5dp"
app:cardCornerRadius="3dp"
app:cardElevation="5dp"
>
<TextView
android:id="#+id/cityid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="50sp"
android:padding="5dp"/>
</android.support.v7.widget.CardView>
This is the myadapter class
public class Myadapter extends RecyclerView.Adapter<Myviewholder> {
ArrayList<String> Citynames;
Context c;
public Myadapter(ArrayList<String> citynames, Context c) {
Citynames = citynames;
this.c = c;
}
#NonNull
#Override
public Myviewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(c).inflate(R.layout.cardview,viewGroup,false);
Myviewholder VH = new Myviewholder(v);
return VH;
}
#Override
public void onBindViewHolder(#NonNull Myviewholder myviewholder, int i) {
myviewholder.nametext.setText(Citynames.get(i));
}
#Override
public int getItemCount() {
return Citynames.size();
}
}
this is my viewholder class
public class Myviewholder extends RecyclerView.ViewHolder {
TextView nametext;
public Myviewholder(#NonNull View itemView) {
super(itemView);
nametext = itemView.findViewById(R.id.cityid);
}
}
This is my main class
public class Feature extends Fragment {
ArrayList<String> Citynames = new ArrayList<> (Arrays.asList("dhaka","rongpur","bagura",
"sylhet","vhola","lalmonirhut","khulna","cumillah","rajshahi"));
public Feature()
{
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.feature,container,false);
RecyclerView recyclerView = view.findViewById(R.id.featurerecyclerid);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Myadapter myadapter = new Myadapter(Citynames,getActivity());
recyclerView.setAdapter(myadapter);
return inflater.inflate(R.layout.feature,container,false);
}
}
No error is showing in my project but not showing the RecyclerView.
ok you just set your your recycler view before the fragment view created,I mostly metion you in your previuous question
set your recyler view in 'onViewCreated' method,see my answer there.And not to post same question again and again,you also can edit your question

Application crashes when I launch the RecyclerView

So I'm building a RecyclerView in android studio that displays an image and a title from a list of objects.
Here is the adapter and the view:
public class FavoritesAdapter extends RecyclerView.Adapter<FavoritesAdapter.ViewHolder>{
private List<RecipeModel> list;
private Context context;
public FavoritesAdapter(List<RecipeModel> list, Context context) {
this.list = list;
this.context = context;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private CircleImageView circleImageView;
private TextView title;
private RelativeLayout relativeLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView=(CircleImageView) itemView.findViewById(R.id.favoritesCircleImage);
title=(TextView) itemView.findViewById(R.id.favoritesTitle);
relativeLayout=(RelativeLayout) itemView.findViewById(R.id.favorites_layout);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_favorites_list_item, viewGroup, false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Glide.with(context)
.asBitmap()
.load(list.get(i).getImage_url())
.into(viewHolder.circleImageView);
viewHolder.title.setText(list.get(i).getTitle());
viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clicking on the item
}
});
}
#Override
public int getItemCount() {
return list.size();
}
}
Here is the XML for the activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FavoritesActivity">
<view class="android.support.v7.app.AlertController$RecycleListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerViewFavorites">
</view>
</RelativeLayout>
And the XML for the list item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:id="#+id/favorites_layout">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/favoritesCircleImage"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/favoritesTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="110dp"
android:layout_marginTop="25dp"
android:text="DummyText"
android:textColor="#000"
android:textSize="17sp" />
</RelativeLayout>
And here is a code snippet of the implementation of the recyclerview:
private void initRecyclerView(){
RecyclerView recyclerView=findViewById(R.id.recyclerViewFavorites);
FavoritesAdapter favoritesAdapter=new FavoritesAdapter(recipeModelList, getApplicationContext());
recyclerView.setAdapter(favoritesAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
However when I launch the application and open the activity the app crashes. The list is fine its not set to a null I've checked that already.
Any ideas?
In the XML layout you have used a RecycleListView. But in the initRecyclerView() method you have initialized a RecylerView. So use a RecyclerView instead of RecycleListView. RecyclerView and RecycleListView are two things.
Replace
<view class="android.support.v7.app.AlertController$RecycleListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerViewFavorites">
</view>
With
<android.support.v7.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerViewFavorites"/>

Using Picasso Images not showing in Recycler view

I am trying to show images from a Firebase database in recycler view in android studio but the images are not displaying. I am not sure where I have gone wrong or what the problem is.
Main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.test.test.AddBrandPage"
android:weightSum="1">
<TextView
android:id="#+id/editText"
android:layout_width="383dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Select your favourite stores..."
android:textAlignment="center"
android:textSize="22sp" />
<LinearLayout
android:id="#+id/alphaindex"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"></LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recylView"
android:layout_width="337dp"
android:layout_height="370dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText2"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="24dp"
android:layout_weight="0.23"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.11"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_skip"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:background="#color/colorPrimary"
android:text="Skip"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
<Button
android:id="#+id/btn_submit"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
android:background="#color/colorPrimary"
android:text="Submit"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
</LinearLayout>
</LinearLayout>
Logo_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardView="http://schemas.android.com/apk/res-auto"
android:id="#+id/logo_container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#android:color/darker_gray"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:visibility="visible"
cardView:layout_collapseParallaxMultiplier="1.0">
<android.support.v7.widget.CardView
android:layout_width="155dp"
android:layout_height="100dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
cardView:cardBackgroundColor="#android:color/white">
<GridLayout
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/img_logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_row="0"
android:paddingBottom="5dp"
android:paddingLeft="2.5dp"
android:paddingRight="2.5dp"
android:paddingTop="5dp">
</ImageView>
</GridLayout>
<CheckBox
android:id="#+id/checkbox"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="130dp"
android:layout_marginTop="66dp"
/>
</android.support.v7.widget.CardView>
</LinearLayout>
LogoItems.java
public class LogoItems {
//declare variables(the items displayed in the layout)
private String logo;//, name;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
}
Main Activity.java
package com.test.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
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.HashMap;
import java.util.List;
public class AddBrandPage extends AppCompatActivity implements OnClickListener {
//declare variables
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private DatabaseReference myRef;
private Button btn_skip;
private Button btn_submit;
//private String name;
//private String url;
List<LogoItems> brandLogo = new ArrayList<>();
//HashMap<String, String> dataSet = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_brand_page);
//initialize variables
btn_skip = (Button) findViewById(R.id.btn_skip);
btn_submit = (Button) findViewById(R.id.btn_submit);
myRef = FirebaseDatabase.getInstance().getReference().child("/brands");
// set the main recyclerview view in the layout
recyclerView = (RecyclerView) findViewById(R.id.recylView);
recyclerView.setHasFixedSize(true);
// set the main layoutManager of the recyclerview
layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
loadLogoImgData();
// set the recycler view adapter
adapter = new LogoAdapter(brandLogo, getBaseContext());
recyclerView.setAdapter(adapter);
//set the listener for the buttons click event
btn_skip.setOnClickListener(this);
btn_submit.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == btn_skip) {
//if skip button clicked close current window and go to user main page
finish();
startActivity(new Intent(getApplicationContext(), UserMainPage.class));
}
}
public void loadLogoImgData(){
brandLogo.clear();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value = brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails = new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
LogoItemsAdapter.java
package com.test.test;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class LogoAdapter extends RecyclerView.Adapter<LogoAdapter.LogoViewHolder> {
List<LogoItems> brandLogo = new ArrayList<>();
// private AddBrandPage addBrandPage;
private Context context;
public LogoAdapter(List <LogoItems> brandLogo, Context context){
this.brandLogo = brandLogo;
this.context = context;
//addBrandPage = (AddBrandPage)context;
}
#Override
public LogoAdapter.LogoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.logo_items,parent,false);
LogoViewHolder logoViewHolder = new LogoViewHolder(view);
return logoViewHolder;
}
#Override
public void onBindViewHolder(LogoAdapter.LogoViewHolder holder, int position) {
//holder.logo.setImageURI(Uri.parse(brandLogo.get(position).getLogo()));
Picasso.with(context).load(brandLogo.get(position).getLogo()).into(holder.logo);
}
#Override
public int getItemCount() {
return brandLogo.size();
}
public static class LogoViewHolder extends RecyclerView.ViewHolder{
//declare variables
public ImageView logo;
CheckBox checkbox;
//private View itemView;
public LogoViewHolder(View itemView){
super(itemView);
//initialize variables inside the constructor
logo = (ImageView)itemView.findViewById(R.id.img_logo);
checkbox = (CheckBox)itemView.findViewById(R.id.checkbox);
// this.itemView = itemView;
}
}
}
your code seems a bit vague like here :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails =
new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails); } }
Change this code to :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
brandLogo.add(value); }
startRecyclerView();
}
Firebase methods are asynchronous, your present code inflates the recylcerview synchronously which means it is loaded before the data has been set and received.
The changed code starts recyclerview asynchronously after the data has been loaded from the database. You can add a progress bar to know the status. You can set it like this (Initialize it before this method and it will be visible by default) :
mProgressBar.setVisibility(View.INVISIBLE);
startRecyclerView();
This way the code looks organised.

StaggeredGridLayoutManager with recyclerview showing only two images per page

I have taken sample code from https://github.com/chrisbanes/cheesesquare as base to show images in StaggeredGridLayoutManager. StaggeredGridLayoutManager with recyclerview showing only two images per page.
I tried almost all ways to show multiple images in full page, but its not working.
Any help would be great.
fragment_cheese_list.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"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.support.android.designlibdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/color_primary_teal">
<!--<android.support.v7.widget.CardView-->
<!--xmlns:card_view="http://schemas.android.com/apk/res-auto"-->
<!--xmlns:android="http://schemas.android.com/apk/res/android"-->
<!--android:id="#+id/card_view"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--card_view:cardUseCompatPadding="true"-->
<!--card_view:cardCornerRadius="8dp"-->
<!--android:layout_marginBottom="16dp">-->
<!--<RelativeLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent">-->
<!--<de.hdodenhof.circleimageview.CircleImageView-->
<!--android:id="#+id/avatar"-->
<!--android:layout_width="#dimen/list_item_avatar_size"-->
<!--android:layout_height="#dimen/list_item_avatar_size"-->
<!--android:layout_marginRight="16dp"/>-->
<ImageView
android:id="#+id/avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:onClick="getImageDetails" />
<TextView
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?attr/textAppearanceListItem"/>
<!--</RelativeLayout>-->
<!--</android.support.v7.widget.CardView>-->
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
CheeseListFragment.java
package com.support.android.designlibdemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
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 java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class CheeseListFragment extends Fragment {
//private RecyclerView.StaggeredGridLayoutManager mLayoutManager;
int cheeseImages[]= {R.drawable.cheese_1,R.drawable.cheese_2,R.drawable.cheese_3,
R.drawable.cheese_4,R.drawable.cheese_5};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_cheese_list, container, false);
RecyclerView rv = (RecyclerView) relativeLayout.findViewById(R.id.recyclerview);
//RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
private void setupRecyclerView(RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
ArrayList<ImageDetails> placeList = getPlaces();
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, 30), placeList));
}
private List<String> getRandomSublist(String[] array, int amount) {
ArrayList<String> list = new ArrayList<>(amount);
Random random = new Random();
while (list.size() < amount) {
list.add(array[random.nextInt(array.length)]);
}
return list;
}
private ArrayList<ImageDetails> getPlaces() {
ArrayList<ImageDetails> details = new ArrayList<>();
for (int index=0; index<30;index++){
details.add(new ImageDetails(Cheeses.getRandomCheeseDrawable()));
}
return details;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
private ArrayList<ImageDetails> mImagesList;
public static class ViewHolder extends RecyclerView.ViewHolder {
public String mBoundString;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString() {
return super.toString() + " '" + mTextView.getText();
}
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items, ArrayList<ImageDetails> imageList) {
// context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
// mBackground = mTypedValue.resourceId;
mValues = items;
mImagesList = imageList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
//view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mBoundString = mValues.get(position);
holder.mTextView.setText(mValues.get(position));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, CheeseDetailActivity.class);
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
context.startActivity(intent);
}
});
holder.mImageView.setImageResource(mImagesList.get(position).getImageUrl());
// Glide.with(holder.mImageView.getContext())
// .load(Cheeses.getRandomCheeseDrawable())
// .fitCenter()
// .into(holder.mImageView);
}
#Override
public int getItemCount() {
return mValues.size();
}
}
}
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
chnage layout height to wrap_content:-
android:layout_height="wrap_content"

Create a recycler view insider a recycler view in android

If I want to create a recycler view insider a recycler view in android, how to handle the view holder in the first container of recycler view and how to handle the transmission in two recycler view? Please give me some suggestion. Thank you very much.
Problem Statement : We have to display three items in parent recycler view. First two items are normal cardViews and the third item is child recycler view.
The top two items are card views and the third item is a list of hotels.
MainActivity.class :
public class **MainActivity** extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
ArrayList<DataModel> items = new ArrayList<>();
items.add(new DataModel("Bus"));
items.add(new DataModel("Flight"));
ArrayList<String> hotelsList=new ArrayList<>();
hotelsList.add("Hotel 1");
hotelsList.add("Hotel 2");
hotelsList.add("Hotel 2");
items.add(new DataModel("Hotels",hotelsList));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
ParentAdapter parentAdapter = new ParentAdapter(items,MainActivity.this);
recyclerView.setAdapter(parentAdapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
DataModel.class
public class DataModel {
private String title;
private ArrayList<String> hotels;
public DataModel(String title){
this.title=title;
}
public DataModel(String title, ArrayList<String> hotels){
this.title=title;
this.hotels=hotels;
}
public String getTitle() {
return title;
}
public ArrayList<String> getHotels() {
return hotels;
}
}
ParentAdapter.class : Parent Recycler View
public class ParentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<DataModel> items;
private Context mContext;
public ParentAdapter(ArrayList<DataModel> items, Context mContext) {
this.items = items;
this.mContext=mContext;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
if (viewType == ViewType.NORMAL_ITEM) {
return new NormalHolder(layoutInflater.inflate(R.layout.normal_view, parent, false));
} else if (viewType == ViewType.HOTELS_LIST_ITEM) {
return new ListHolder(layoutInflater.inflate(R.layout.list_view, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int cardType = getItemViewType(position);
switch (cardType) {
case ViewType.NORMAL_ITEM:
NormalHolder normalHolder=(NormalHolder) holder;
normalHolder.title.setText(items.get(position).getTitle());
break;
case ViewType.HOTELS_LIST_ITEM:
ListHolder listHolder=(ListHolder) holder;
HotelCardAdapter hotelCardAdapter = new HotelCardAdapter(mContext, items.get(position).getHotels());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
listHolder.hotelsList.setLayoutManager(linearLayoutManager);
listHolder.hotelsList.setAdapter(hotelCardAdapter);
break;
}
}
private interface ViewType {
int NORMAL_ITEM = 0;
int HOTELS_LIST_ITEM = 1;
}
#Override
public int getItemViewType(int position) {
if (position == 0 || position == 1) {
return ViewType.NORMAL_ITEM;
} else return ViewType.HOTELS_LIST_ITEM;
}
#Override
public int getItemCount() {
return items.size();
}
private class NormalHolder extends RecyclerView.ViewHolder {
TextView title;
public NormalHolder(View inflate) {
super(inflate);
title=inflate.findViewById(R.id.title);
}
}
private class ListHolder extends RecyclerView.ViewHolder {
RecyclerView hotelsList;
public ListHolder(View inflate) {
super(inflate);
hotelsList = inflate.findViewById(R.id.hotel_list);
}
}
}
normal_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="6dp">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bus"
android:textColor="#color/colorPrimary"
android:textSize="20sp"/>
<Button
android:id="#+id/view_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:gravity="center"
android:text="View All"
android:textSize="12sp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp">
<TextView
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hotels"
android:textColor="#color/colorPrimary"
android:textSize="17sp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/hotel_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:layout_marginTop="12dp"
android:orientation="horizontal"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
HotelCardAdapter.class : Child Recycler View
public class HotelCardAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<String> hotelsObject;
private Context context;
public HotelCardAdapter(Context context, ArrayList<String> hotelsObject) {
this.hotelsObject = hotelsObject;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
return new HotelCarouselHolder(layoutInflater.inflate(R.layout.hotel_carousel_item, null));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
HotelCarouselHolder hotelCarouselHolder = (HotelCarouselHolder) holder;
hotelCarouselHolder.title.setText(hotelsObject.get(position));
}
#Override
public int getItemCount() {
return hotelsObject.size();
}
private class HotelCarouselHolder extends RecyclerView.ViewHolder {
private TextView title;
public HotelCarouselHolder(View inflate) {
super(inflate);
title = inflate.findViewById(R.id.title);
}
}
}
hotel_carousel_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<RelativeLayout
android:id="#+id/hotel_details_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/hotel_image"
android:layout_width="256dp"
android:layout_height="144dp"
android:scaleType="centerCrop"
android:src="#999999"/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/hotel_image"
android:textSize="16sp"
android:text="Hotels 1"/>
</RelativeLayout>
</RelativeLayout>
Hope this helps!!