android: receive exception when view next tab - android

I want to add Recyclerview inside fragment then after that want to add fragment inside viewpager.So i follow tutorial on youtube.after compile..recyclerview is display but when i go to next tabs,exception appear.Hope you guys can help me solve this problem.
ERROR
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.recyclerviewpagerfragment, PID: 3705
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 3705 SIG: 9
Application terminated.
MainActivity.java
package com.example.user.recyclerviewpagerfragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.example.user.recyclerviewpagerfragment.Fragments.CrimeFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DramaFragment;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initialize view pager.
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager_id);
this.addPages(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_id);
//it gonna occupy the whole screen..
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(listener(viewPager));
}
// add all pages
private void addPages(ViewPager pager){
FragPagerAdapter adapter = new FragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new CrimeFragment());
adapter.addPage(new DramaFragment());
adapter.addPage(new DocumentaryFragment());
//set adapter to pager
pager.setAdapter(adapter);
}
private TabLayout.OnTabSelectedListener listener(final ViewPager pager){
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
FragPagerAdapter.java
package com.example.user.recyclerviewpagerfragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class FragPagerAdapter extends FragmentPagerAdapter{
//create arraylist..where its gonna hol fragment.
ArrayList<Fragment> pages = new ArrayList<>();
public FragPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
// add a page
public void addPage(Fragment f){
pages.add(f);
}
//set title for tab
#Override
public CharSequence getPageTitle(int position) {
return pages.get(position).toString();
//return super.getPageTitle(position);
}
}
MyRecyclerAdapter.java
package com.example.user.recyclerviewpagerfragment.Recycler;
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.Toast;
import com.example.user.recyclerviewpagerfragment.R;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context context;
ArrayList<Movie> movies;
public MyRecyclerAdapter(Context context, ArrayList<Movie> movies) {
this.context = context;
this.movies = movies;
}
//initialize holder.
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyViewHolder holder = new MyViewHolder(view);
return holder;
//return null;
}
//bind data to views
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(movies.get(position).getImage());
holder.img.setImageResource(movies.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(context,movies.get(position).getName(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return movies.size();
}
}
MyViewHolder.java
package com.example.user.recyclerviewpagerfragment.Recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.user.recyclerviewpagerfragment.R;
/**
* Created by User on 10/4/2016.
*/
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView img;
TextView nameTxt;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);
img = (ImageView) itemView.findViewById(R.id.movieImage);
//above...if want to make click on nameTxt,can change itemView to nameTxt
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(view,getLayoutPosition());
}
}
DocumentaryFragment.java
package com.example.user.recyclerviewpagerfragment.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.user.recyclerviewpagerfragment.R;
import com.example.user.recyclerviewpagerfragment.Recycler.Movie;
import com.example.user.recyclerviewpagerfragment.Recycler.MyRecyclerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class DocumentaryFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//call view
View view = inflater.inflate(R.layout.documentary_fragment,null);
//recyclerview
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerDocumentary);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//set Adapter
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(),getDocumentaryMovies()));
return view;
//return super.onCreateView(inflater, container, savedInstanceState);
}
private ArrayList<Movie> getDocumentaryMovies() {
//collection of crime movies.
ArrayList<Movie> movies = new ArrayList<>();
//single movie
Movie movie = new Movie("Crime:tank5",R.drawable.e);
//add to collection..
movies.add(movie);
movie = new Movie("Crime:tank6",R.drawable.f);
movies.add(movie);
return movies;
/*
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
*/
}
//set title for the fragment
#Override
public String toString() {
return "Documentary";
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.user.recyclerviewpagerfragment.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<!-- add above for adding tablayout -->
<android.support.design.widget.TabLayout
android:id="#+id/tab_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<!-- add above for adding viewpager -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Documentary_fragment.xml
<android.support.v7.widget.LinearLayoutCompat
android:id="#+id/mRecyclerDocumentary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></android.support.v7.widget.LinearLayoutCompat> </LinearLayout>
Model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="10dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/movieImage"
android:padding="10dp"
android:src="#drawable/a"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameTxt"
android:padding="10dp"
android:textColor="#color/colorAccent"
android:layout_below="#+id/movieImage"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="this tanks is awsome no need to jurge it."
android:id="#+id/descTxt"
android:layout_below="#+id/nameTxt"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="TV Show"
android:id="#+id/posTxt"
android:padding="10dp"
android:layout_below="#id/movieImage"
android:layout_alignParentRight="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chk"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>

the error is
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
As it says the problem is in DocumentaryFragment, you are casting a LinearLayout to a ReciclerView, you should provide us that Fragment.
Hope it helps, I would like to comment but I do not have the requisites yet.

Related

Fragment not displaying the whole recyclerview. Its displaying only one cardview

The fragment only displays one cardview when I am trying to retrieve it from the news API.
Here is the code.
Main Activity
package com.manish.newapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create an instance of the tab layout from the view.
TabLayout tabLayout = findViewById(R.id.tab_layout);
// Set the text for each tab.
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label4));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label5));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label6));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label7));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label8));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label9));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label10));
// Set the tabs to scroll through the entire layout.
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// Use PagerAdapter to manage page views in fragments.
// Each page is represented by its own fragment.
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
// Setting a listener for clicks.
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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) {
}
});
}
}
TabNews Fragment
package com.manish.newapp.Fragments;
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 android.widget.Toast;
import com.manish.newapp.Adapter;
import com.manish.newapp.ApiClient;
import com.manish.newapp.Models.Articles;
import com.manish.newapp.Models.Headlines;
import com.manish.newapp.Models.Source;
import com.manish.newapp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TabNews1 extends Fragment {
View v;
RecyclerView recyclerView;
final String API_KEY = "5a1ad719eee94e7ba60d19b51f4ff159";
String sources = "bbc-news";
Adapter adapter;
List<Articles> articles = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// String country = getCountry();
// retrieveJson(country,API_KEY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_tab_news1, container, false);
recyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
String country = getCountry();
retrieveJson(country,API_KEY);
// retrieveJson(sources,API_KEY);
// Inflate the layout for this fragment
return v;
}
public void retrieveJson(String country, String apiKey){
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(country,apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null){
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(),articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
adapter Class
package com.manish.newapp;
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 androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.manish.newapp.Models.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_recycler,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
Articles art = articles.get(position);
holder.txtTitle.setText(art.getTitle());
holder.txtDescription.setText(art.getDescription());
holder.txtDate.setText(art.getPublishedAt());
String imageUrl = art.getUrlToImage();
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtTitle, txtDescription, txtDate, txtTime;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.title_text);
txtDescription = (TextView)itemView.findViewById(R.id.desc);
txtTime = (TextView)itemView.findViewById(R.id.time);
txtDate = (TextView)itemView.findViewById(R.id.date);
imageView = (ImageView)itemView.findViewById(R.id.image_news);
cardView = (CardView)itemView.findViewById(R.id.cardView);
}
}
}
Pager Adapter class
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.manish.newapp.Fragments.TabNews1;
import com.manish.newapp.Fragments.TabNews10;
import com.manish.newapp.Fragments.TabNews2;
import com.manish.newapp.Fragments.TabNews3;
import com.manish.newapp.Fragments.TabNews4;
import com.manish.newapp.Fragments.TabNews5;
import com.manish.newapp.Fragments.TabNews6;
import com.manish.newapp.Fragments.TabNews7;
import com.manish.newapp.Fragments.TabNews8;
import com.manish.newapp.Fragments.TabNews9;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(#NonNull FragmentManager fm,int NumOfTabs) {
super(fm, NumOfTabs);
this.mNumOfTabs = NumOfTabs;
}
#NonNull
/**
* Return the Fragment associated with a specified position.
*
* #param position
*/
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return new TabNews1();
case 1 : return new TabNews2();
case 2 : return new TabNews3();
case 3 : return new TabNews4();
case 4 : return new TabNews5();
case 5 : return new TabNews6();
case 6 : return new TabNews7();
case 7 : return new TabNews8();
case 8 : return new TabNews9();
case 9 : return new TabNews10();
default: return null;
}
}
/**
* Return the number of views available.
*/
#Override
public int getCount() {
return mNumOfTabs;
}
}
Here are my layout files.
item_recycler.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardView"
android:layout_margin="16dp"
android:padding="10dp"
app:cardElevation="4dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image_news"
android:src="#drawable/image"
android:scaleType="centerCrop"/>
<!-- <FrameLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:id="#+id/frame_layout"-->
<!-- android:layout_below="#+id/image_news"-->
<!-- android:padding="5dp">-->
<!-- <RelativeLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content">-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="20dp"
android:layout_below="#+id/image_news"
android:textStyle="bold"
android:id="#+id/title_text"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/desc"
android:text="DESCRIPTION"
android:layout_marginTop="10dp"
android:textSize="14dp"
android:layout_below="#+id/title_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/time"
android:layout_below="#+id/desc"
android:text="TIME"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:layout_below="#+id/time"
android:text="DATE"
android:layout_marginTop="5dp"/>
<!-- </RelativeLayout>-->
<!-- </FrameLayout>-->
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
fragment_tab_news1.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"
tools:context=".Fragments.TabNews1"
android:background="#color/colorBackground">
<!-- TODO: Update blank fragment layout -->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- <TextView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:text="BBC NEWS"-->
<!-- android:textStyle="bold"-->
<!-- android:textSize="17sp"-->
<!-- android:layout_marginLeft="16dp"-->
<!-- android:layout_marginRight="16dp"-->
<!-- android:layout_marginTop="10dp"-->
<!-- android:fontFamily="sans-serif-light"/>-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
Mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity"
android:id="#+id/relative_main"
android:padding="16dp"
>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Please help me with this, I am unable to find whats wrong here.

I add SearchView in Toolbar and Using Tab Layout in The Activity and I want SearchView to work in both Fragment that I added as Tab

I am Using a Tab Layout with two fragments both have Recycler View and also added Search View in Tab Layout but here I am facing a problem, I want Search View to work on Both Fragment that I added As Tab but Search View is in another activity(Toolbar) and both fragments are different
Activity Having Tabs(LanguageChooser Activity)
package com.piyushjaiswal.lyricswala;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.material.tabs.TabLayout;
public class LanguageChooser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language_chooser);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SectionPagerAdapter pagerAdapter = new SectionPagerAdapter(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
ViewPager pager = findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
}
private class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(#NonNull FragmentManager fm, int behaviour) {
super(fm,behaviour);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Hindi();
case 1:
return new Punjabi();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0: return getResources().getText(R.string.Hindi);
case 1:return getResources().getText(R.string.Punjabi);
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.toolbar,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
System.exit(1);
}
}
XML CODE OF LanguageChooserActivity
<?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=".LanguageChooser">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/toolbar"
android:background="#color/colorAccent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
app:elevation="0dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabs"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:id="#+id/pager"
android:layout_height="match_parent" />
</LinearLayout>
My Toolbar having Search View
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_Search"
android:title="#string/search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.widget.SearchView"
/>
</menu>
XML code of first Tab(Fragment) named as Hindi
<?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=".Hindi">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progressbar"
android:visibility="visible"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Java Code of Tab(Fragment) named as Hindi
package com.piyushjaiswal.lyricswala;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.app.SearchManager;
import android.widget.ProgressBar;
import androidx.appcompat.widget.SearchView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class Hindi extends Fragment {
View v;
private RecyclerView myRecyclerview;
private List<Contact> listContact = new ArrayList<>();
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference();
private RecyclerViewAdapter recyclerViewAdapter;
private ProgressBar progressBar;
public Hindi() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_hindi,container,false);
progressBar= v.findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
myRecyclerview = v.findViewById(R.id.recyclerView);
myRecyclerview.setHasFixedSize(true);
myRecyclerview.setItemViewCacheSize(10);
recyclerViewAdapter = new RecyclerViewAdapter(getContext(),listContact);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
myRecyclerview.setLayoutManager(layoutManager);
myRecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myRef.child("Hindi").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
listContact.add(dataSnapshot1.getValue(Contact.class));
}
recyclerViewAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
Recycler View Adapter
package com.piyushjaiswal.lyricswala;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<Contact> mData;
private List<Contact> mDataFull;
public RecyclerViewAdapter(Context mContext, List<Contact> mData) {
this.mContext = mContext;
this.mData = mData;
mDataFull = new ArrayList<>(mData);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_songs,parent,false);
MyViewHolder vHolder= new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(mData.get(position).getName(),mData.get(position).getPhone(),mData.get(position).getUrl(),mData.get(position).getLyrics());
}
#Override
public int getItemCount() {
return mData.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView tv_name;
private TextView tv_phone;
private ImageView imageView;
MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = (TextView) itemView.findViewById(R.id.name_contact);
tv_phone = (TextView) itemView.findViewById(R.id.phone_contact);
imageView = (ImageView) itemView.findViewById(R.id.img_contact);
}
private void setData(final String name, final String phone, String url, final String Lyrics){
Glide.with(itemView.getContext()).load(url).into(imageView);
this.tv_phone.setText(phone);
this.tv_name.setText(name);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(),LyricsActivit.class);
intent.putExtra("Lyrics",Lyrics);
intent.putExtra("albumname",phone);
intent.putExtra("songname",name);
itemView.getContext().startActivity(intent);
}
});
}
}
}
Screen Shot of My ActivityApp Output
I want above toolbar search view to work on tabs(fragment) Hope I explain my problem
Create a view pager and tab layout together. it will be resolved.Here is an example.

Null point exception with a recyclerview adapter

The code does not have any error... But when I run the application on my phone I am getting a null point exception with the recycler view adapter and I do not understand which data is null
I have tried to recreate a layout using the recyclerview adapter but it does not work
RecyclerViewAdapter.java
package com.example.schedule;
/*
* File to help create the recycler view items to be viewed
* Should help with the iteration
* */
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.view.menu.MenuView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import org.w3c.dom.Text;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private ArrayList<String> mScheduleNames = new ArrayList<>();
private ArrayList<String> mScheduleImages = new ArrayList<>();
private Context mContext;
private final String TAG = "RecyclerViewAdapter";
public RecyclerViewAdapter(Context context, ArrayList<String> scheduleNames, ArrayList<String> scheduleImages) {
mScheduleNames = scheduleNames;
mScheduleImages = scheduleImages;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.each_element, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "OnBindViewHolder: called.");
Glide.with(mContext)
.load(mScheduleImages.get(position))
.asBitmap()
.into(holder.scheduleImage);
holder.scheduleName.setText(mScheduleImages.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Onclicked: clicked on:" + mScheduleImages.get(position));
Toast.makeText(mContext, mScheduleImages.get(position), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mScheduleImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView scheduleImage;
TextView scheduleName;
LinearLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
scheduleImage = itemView.findViewById(R.id.schedule_image);
scheduleName = itemView.findViewById(R.id.schedule_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Layout I want recycled
eachelement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parent_layout">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/schedule_image"
android:layout_width="135dp"
android:layout_height="131dp"
android:src="#drawable/watch"
app:civ_border_color="#FF000000" />
<TextView
android:id="#+id/schedule_name"
android:layout_width="match_parent"
android:layout_height="131dp"
android:layout_weight="1"
android:fontFamily="casual"
android:gravity="center"
android:text="#string/scheduleNames"
android:textSize="18sp"
android:layout_toRightOf="#+id/schedule_image"/>
</RelativeLayout>
Schedules.java
this class should recycle the layout above within the fragment below
package com.example.schedule;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Schedules extends Fragment {
private static final String TAG = "AddingEvents";
private ArrayList<String> mScheduleNames = new ArrayList<>();
private ArrayList<String> mScheduleImageUrls = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
initImageBitmaps();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_schedules, container, false);
}
private void initImageBitmaps(){
Log.d(TAG, "initImageBitmaps: preparing image bitmaps.");
mScheduleNames.add("Steve");
mScheduleImageUrls.add("https://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg");
mScheduleNames.add("Bella");
mScheduleImageUrls.add("https://www.crockerriverside.org/sites/main/files/imagecache/square/main-images/camera_lense_0.jpeg");
mScheduleNames.add("Carre");
mScheduleImageUrls.add("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg/691px-Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg");
initRecyclerView();
}
private void initRecyclerView(){
Log.d(TAG, "initRecyclerView: init recyclerview.");
RecyclerView recyclerView = getView().findViewById(R.id.recyclerviews);
//problem
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
recyclerView.setAdapter(adapter);
//problem
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
fragment_schedules.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"
tools:context=".Schedules"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="113dp"
android:fontFamily="casual"
android:gravity="center"
android:text="#string/Schedules"
android:textSize="18sp"
tools:targetApi="jelly_bean" />
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerviews">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Navigator.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".Navigator">
<FrameLayout
android:id="#+id/fragment_area"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigator">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="9dp"
android:layout_marginRight="9dp"
android:background="#android:color/darker_gray"
android:textAlignment="gravity"
app:menu="#menu/bottom_nav"
android:layout_alignParentBottom="true">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
Navigator.java
This class is supposed to help navigate through the fragments
Schedules is one of the fragments
package com.example.schedule;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class Navigator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigator);
BottomNavigationView bottom_nav = findViewById(R.id.bottom_navigator);
bottom_nav.setOnNavigationItemSelectedListener(newListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
new Schedules()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener newListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.schedule:
selectedFragment = new Schedules();
break;
case R.id.add:
selectedFragment = new AddingEvents();
break;
case R.id.profile:
selectedFragment = new Profile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
selectedFragment).commit();
return true;
}
};
}
this is the error I am getting
D/AddingEvents: initImageBitmaps: preparing image bitmaps.
initRecyclerView: init recyclerview.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schedule, PID: 16701
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.schedule/com.example.schedule.Navigator}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.schedule.Schedules.initRecyclerView(Schedules.java:60)
at com.example.schedule.Schedules.initImageBitmaps(Schedules.java:55)
at com.example.schedule.Schedules.onCreateView(Schedules.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2539)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1227)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1293)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:710)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2063)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1853)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1808)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1715)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2616)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2572)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:525)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:176)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1245)
at android.app.Activity.performStart(Activity.java:6391)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2529)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5763) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
I/System: FinalizerDaemon: finalize objects = 81
I/Process: Sending signal. PID: 16701 SIG: 9
Application terminated.
I expect a recycled schedule with the provided details
In Schedules.java with the initBitmaps() method
I think the issue is because I am using fragments but I want the recycle
to happen there not within the activity
Change to this
public class Schedules extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater . inflate (R.layout.fragment_schedules, container, false);
initImageBitmaps();
RecyclerView recyclerView = view.findViewById (R.id.recyclerviews);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager (getActivity()));
return view;
}
}

actionbar is not showing hide feature when i use grid layout with appbar layout

i am using AppBarLayout. it has a ViewPager in which i have added four fragments two fragments have recyclerView in them. and one has GridView. when i am on the fragment with RecyclerView the ActionBar hides when i scroll list up, but in case of gridview fragment this doesn't happen. ActionBar remains still at its position.
please help me! thanks in advance.
MainActivity
package com.bajpays.financemanager;
import android.support.design.internal.NavigationMenu;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TabLayout tabLayout;
DrawerLayout drawerLayout;
NavigationView navigationView;
ViewPager viewPager;
Toolbar toolbar;
CircleImageView img_user1,img_user2,img_user3,img_user4,img_user5,img_activeuser;
NavigationView navview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar=getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.grouppic);
actionBar.setDisplayShowHomeEnabled(true);
viewPager=(ViewPager)findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
if (viewPager!=null){
setUpViewPager(viewPager);
}
tabLayout=(TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
navigationView=(NavigationView) findViewById(R.id.navigatioview);
if (navigationView != null) {
setupDrawerContent(navigationView);
drawerLayout=(DrawerLayout)findViewById(R.id.drawer);
}
navview=(NavigationView)findViewById(R.id.navigatioview);
View headerview=navview.getHeaderView(0);
RelativeLayout header=(RelativeLayout) headerview.findViewById(R.id.header);
img_activeuser=(CircleImageView)headerview.findViewById(R.id.img_icon_activeuser);
img_user1=(CircleImageView)headerview.findViewById(R.id.img_icon_user1);
img_user2=(CircleImageView)headerview.findViewById(R.id.img_icon_user2);
img_user3=(CircleImageView)headerview.findViewById(R.id.img_icon_user3);
img_user4=(CircleImageView)headerview.findViewById(R.id.img_icon_user4);
img_user5=(CircleImageView)headerview.findViewById(R.id.img_icon_user5);
img_user1.setTag(R.drawable.deep);
img_user2.setTag(R.drawable.grouppic);
img_user3.setTag(R.drawable.indelhi);
img_user4.setTag(R.drawable.kanishk);
img_user5.setTag(R.drawable.tshirt);
img_user1.setOnClickListener(this);
img_user2.setOnClickListener(this);
img_user3.setOnClickListener(this);
img_user4.setOnClickListener(this);
img_user5.setOnClickListener(this);
}
static class MyAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment,String title){
fragments.add(fragment);
titles.add(title);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
public void setUpViewPager(ViewPager viewPager){
MyAdapter adapter=new MyAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment_Home(),"Home");
adapter.addFragment(new Fragment_Catagory(),"Category");
adapter.addFragment(new Fragment_Top5(),"Top 5 Expences");
adapter.addFragment(new Fragment_Statistics(),"Statistics");
viewPager.setAdapter(adapter);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
}
Fragment with grid layout
package com.bajpays.financemanager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Bajpay's on 7/22/2016.
*/
public class Fragment_Home extends Fragment {
View view;
ArrayList<Model_Grid> grids;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_home, container, false);
grids=makegrids();
GridAdapter adapter=new GridAdapter(this.getActivity(),grids);
GridView gridView=(GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(adapter);
Toast.makeText(this.getActivity(), "oncreate of home rns", 200).show();
return view;
}
public ArrayList<Model_Grid> makegrids()
{
ArrayList<Model_Grid> grids=new ArrayList<>();
grids.add(new Model_Grid(R.drawable.cheese_1, "food"));
grids.add(new Model_Grid(R.drawable.cheese_2,"cloth"));
grids.add(new Model_Grid(R.drawable.cheese_3,"outing"));
grids.add(new Model_Grid(R.drawable.cheese_4,"bank"));
grids.add(new Model_Grid(R.drawable.cheese_5,"travel"));
grids.add(new Model_Grid(R.drawable.cheese_1,"rent"));
grids.add(new Model_Grid(R.drawable.cheese_2,"health"));
grids.add(new Model_Grid(R.drawable.cheese_3,"makeup"));
grids.add(new Model_Grid(R.drawable.cheese_4,"home"));
grids.add(new Model_Grid(R.drawable.cheese_5,"daily"));
grids.add(new Model_Grid(R.drawable.cheese_1,"study"));
grids.add(new Model_Grid(R.drawable.cheese_5,"electronics"));
grids.add(new Model_Grid(R.drawable.cheese_4,"mobile"));
grids.add(new Model_Grid(R.drawable.ic_forum,"add new"));
return grids;
}
}
class GridAdapter extends BaseAdapter{
Context context;
LayoutInflater inflater;
View view;
ImageView imageView;
TextView gridname;
ArrayList<Model_Grid> grids=new ArrayList<>();
GridAdapter(Context context,ArrayList<Model_Grid> gridlist){
this.context=context;
grids=gridlist;
inflater=LayoutInflater.from(context);
}
#Override
public int getCount() {
return grids.size();
}
#Override
public Object getItem(int position) {
return grids.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view=inflater.inflate(R.layout.dapter_for_home,null);
imageView=(ImageView)view.findViewById(R.id.grid_img);
gridname=(TextView)view.findViewById(R.id.grid_name);
imageView.setImageResource(grids.get(position).getImageid());
gridname.setText(grids.get(position).getGridName());
return view;
}
}
Layout of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinatorlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#659eaf"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="enterAlways|scroll|snap" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff75cc"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigatioview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header"
app:menu="#menu/menu"/>
</android.support.v4.widget.DrawerLayout>
layout of fragment
<?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="match_parent">
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:columnWidth="120dp"
android:stretchMode="spacingWidthUniform"
android:paddingBottom="50dp">
</GridView>
</LinearLayout>
it works only on Lollipop add this code-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
gridview.setNestedScrollingEnabled(true);
}
otherwise try to put your grid layout inside NestedScrollview. Hope this will help.

Why nothing is appearing on Screen and how to solve this issue while using RecyclerView in Android

after 2 hours of watching tutorial on RecyclerView I just stuck on the blank Screen. I just want that my code runs and I get the required Output. Also I need some information about cardView. Any help would be appreciated.
here is my code
Adapter.java
package bhanu13.flyourskills;
import android.content.Context;
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.ImageButton;
import android.widget.TextView;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private final LayoutInflater inflator;
List<RowContent> data= Collections.emptyList();
public Adapter(Context context,List<RowContent> data) {
this.data=data;
inflator=LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.one_row,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.firstImageButton.setBackgroundResource(R.drawable.himi);
holder.secondImageButton.setBackgroundResource(R.drawable.himi);
holder.textView.setText("A");
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
ImageButton firstImageButton;
ImageButton secondImageButton;
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
firstImageButton= (ImageButton) itemView.findViewById(R.id.first_image_button);
secondImageButton= (ImageButton) itemView.findViewById(R.id.second_image_button);
textView= (TextView) itemView.findViewById(R.id.textview);
}
}
}
Fregment's code
package bhanu13.flyourskills;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class ButtonsFregment extends Fragment {
RecyclerView recyclerView;
Adapter adapter;
ImageButton firstImageButton;
ImageButton secondImageButton;
Context context;
private List<RowContent> data;
public ButtonsFregment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buttons_fregment, container, false);
recyclerView= (RecyclerView) view.findViewById(R.id.recycler_view);
adapter=new Adapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public List<RowContent> getData() {
List<RowContent> rowContents=new ArrayList<>();
RowContent rowContent=new RowContent();
rowContent.firstImageID=R.drawable.himi;
rowContent.secondImageID=R.drawable.himi;
rowContents.add(rowContent);
return rowContents;
}
}
One_row.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="horizontal">
<ImageButton
android:id="#+id/first_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/second_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dummy"
android:id="#+id/textview"/>
</LinearLayout>
and Fragment's 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"
tools:context=".ButtonsFregment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
MainActivity.java
package bhanu13.flyourskills;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
for (int i = 0; i < 4; i++) {
Fragment buttonsFragment = new ButtonsFregment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.linear_fragments, buttonsFragment).commit();
}
}
}
Activity
package com.example.usmank.myapplication;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressDialog pd=new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
pd.show();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.framLayout,new YourFragment());
fragmentTransaction.commit();
if(pd.isShowing()) {
pd.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
fragment
package com.example.usmank.myapplication;
/**
* Created by usmank on 3/8/2016.
*/
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class YourFragment extends Fragment {
RecyclerView recyclerView;
Adapter adapter;
ImageButton firstImageButton;
ImageButton secondImageButton;
Context context;
public YourFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buttons_fragment, container, false);
recyclerView= (RecyclerView) view.findViewById(R.id.recycler_view);
adapter=new Adapter(getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
}
adapter
package com.example.usmank.myapplication;
/**
* Created by usmank on 3/8/2016.
*/
import android.content.Context;
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.ImageButton;
import android.widget.TextView;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private final LayoutInflater inflator;
public Adapter(Context context) {
inflator=LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.one_row,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.firstImageButton.setBackgroundResource(R.mipmap.ic_launcher);
holder.secondImageButton.setBackgroundResource(R.mipmap.ic_launcher);
holder.textView.setText("A");
}
#Override
public int getItemCount() {
//data.size()
return 10;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
ImageButton firstImageButton;
ImageButton secondImageButton;
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
firstImageButton= (ImageButton) itemView.findViewById(R.id.first_image_button);
secondImageButton= (ImageButton) itemView.findViewById(R.id.second_image_button);
textView= (TextView) itemView.findViewById(R.id.textview);
}
}
}
fragment 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"
tools:context=".ButtonsFregment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
recycler 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="horizontal">
<ImageButton
android:id="#+id/first_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/second_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dummy"
android:id="#+id/textview"/>
</LinearLayout>
activty 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/framLayout">
</FrameLayout>
</RelativeLayout>
gredle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.usmank.myapplication"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.1.1'
}
I am using like this it is working perfectly please change according to your requirments
Recycler Adapter is
package adapter;
import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
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 com.google.android.gms.maps.model.LatLng;
import com.mycompany.locationsharing.R;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import common.CommUtil;
import common.SendNotifications;
/**
* Created by usmank on 1/15/2016.
*/
public class FriendsListsAdapter extends RecyclerView.Adapter<FriendsListsAdapter.ViewHolder> {
private final Activity activity;
private final JSONArray arrayFriendList;
private static final String TAG="MY_FRIEND_ID";
private FragmentTransaction fragmentTransaction;
private LatLng mLatLng;
public FriendsListsAdapter(Activity activity, JSONArray arrayFriendList,LatLng mLatLng) {
this.activity = activity;
this.arrayFriendList = arrayFriendList;
this.mLatLng = mLatLng;
}
static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView friendsName;
private final ImageView ivFriendImage;
public ViewHolder(View v) {
super(v);
friendsName = (TextView) v.findViewById(R.id.tvFriendsName);
ivFriendImage= (ImageView) v.findViewById(R.id.ivFriendsImage);
v.setClickable(true);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.recycler_item, viewGroup, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
try {
viewHolder.friendsName.setText(arrayFriendList.getJSONObject(i).get("name").toString());
Picasso.with(activity).load("https://graph.facebook.com/"+ arrayFriendList.getJSONObject(i).get("id").toString()+"/picture")
.placeholder(R.drawable.placeholder).resize(160, 170).into(viewHolder.ivFriendImage);
CommUtil.showDebugLogs(TAG,arrayFriendList.getJSONObject(i).get("id").toString());
} catch (JSONException e) {
CommUtil.showExceptionTrace(e);
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SendNotifications sendNotifications = new SendNotifications(activity,arrayFriendList.getJSONObject(i).get("name").toString());
String[] parems = {arrayFriendList.getJSONObject(i).get("id").toString(),String.valueOf(mLatLng.latitude),String.valueOf(mLatLng.longitude)};
sendNotifications.execute(parems);
} catch (JSONException e) {
CommUtil.showExceptionTrace(e);
}
}
});
}
#Override
public int getItemCount() {
return arrayFriendList.length();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
and where i am using this
recyclerFriendList.setAdapter(new FriendsListsAdapter(getActivity(), friendsJsonArray,new LatLng(latitude,longitude)));
and recycler_item.xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
android:elevation="4dp"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#mipmap/ic_launcher"
android:paddingRight="7dp"
android:id="#+id/ivFriendsImage"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/tvFriendsName"
android:text="Hello My Friend"
android:textColor="#000"
xmlns:android="http://schemas.android.com/apk/res/android" />
</LinearLayout>
</android.support.v7.widget.CardView>
and where recycler view is used
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerFriendsList"
android:background="#e7e7e7"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</android.support.v7.widget.RecyclerView>
and please also in import recycler library
and carview is also used in it which is the component of material design which can be used to beautify

Categories

Resources