Ajit Hogade Ajit Hogade - 11 days ago 5
Android Question

Navigation drawer Recycler View null pointer Exception

I am working with recycleView as per material design tutorial,I have done all accordingly but my logCat says:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.portal.college.myapplication, PID: 6541 java.lang.NullPointerException
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5229)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4453)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1370)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2900)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3071)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1067)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)


main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/app_bar"
layout="@layout/app_bar_main" />
</LinearLayout>
<fragment
android:id="@+id/fragment_navigation_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="@layout/fragment_navigation_drawer"
android:name="com.portal.college.myapplication.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer"
/>
</android.support.v4.widget.DrawerLayout>


fragment layout xml file is:
fragment_navigation_drawer.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:background="#8c8c8c"
tools:context="com.portal.college.myapplication.NavigationDrawerFragment">

<include
android:id="@+id/nav_head"
layout="@layout/nav_header_main" />
<android.support.v7.widget.RecyclerView
android:id="@+id/drawerList"
android:layout_width="match_parent"

android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>

</RelativeLayout>


Now MainActivity.java

package com.portal.college.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView recyclerView;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

drawerFragment.setUp((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});

}

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_settings) {
return true;
}
if(id == R.id.search) {
startActivity(new Intent(this, SearchActivity.class));
}

return super.onOptionsItemSelected(item);

}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}


NavigationDrawerFragment.java

package com.portal.college.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
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.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class NavigationDrawerFragment extends Fragment {
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView recyclerView;
private VivzAdapter adapter;
public NavigationDrawerFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer,container,false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new VivzAdapter(getActivity(),getData());

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int icons[] = {
R.drawable.ic_menu_camera,
R.drawable.ic_menu_gallery,
R.drawable.ic_menu_manage,
R.drawable.ic_menu_send};
String[] title = {"Camera","Gallery","Settings","Send"};
for(int i=0;i<title.length && i<icons.length;i++){
Information current = new Information();
current.iconId = icons[i];
current.title = title[i];
data.add(current);
}
return data;

}


public void setUp(DrawerLayout drawerLayout,Toolbar toolbar) {
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
public void onDrawerOpened(View drawerView){
super.onDrawerOpened(drawerView);

}
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);

}

};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {

@Override
public void run() {
mDrawerToggle.syncState();
}
});
/* containerView = getActivity().findViewById(fragment_id);
mDrawerLayout=drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.open_drawer,R.string.close_drawer){
@SuppressLint("NewApi")
public void onDrawerOpened(View drawerView){
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer){
mUserLearnedDrawer = false;
saveToPreferences(getActivity(),KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
*/
}

}


Adapter class is VivzAdapter.cjava

package com.portal.college.myapplication;

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.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
* Created by admin on 08-Feb-16.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder>{
private final LayoutInflater inflater;
List<Information> data = Collections.emptyList();

public VivzAdapter(Context context,List<Information> data){
inflater=LayoutInflater.from(context);
this.data=data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row,parent,false);
MyViewHolder holder = new MyViewHolder(view);
return null;
}


@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.id.setImageResource(current.iconId);
}

@Override
public int getItemCount() {

return data.size();

}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView id;

public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
id = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}


The list Item class is Information.java

package com.portal.college.myapplication;

/**
* Created by admin on 08-Feb-16.
*/
public class Information {
int iconId;
String title;
}


List Row layout is custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_menu_camera"/>
<TextView
android:id="@+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera"
/>
</LinearLayout>


I have gone through most of the solution on stackoverflow which are regarding the same issue, but I failed here.

One thing I noticed that in
VivzAdapter.java
, the function name
getItemCount()
which is getting the data
Count
return the
data.size()
, when I change it to return
0
it works by without
recyclerView
, but when returned with
data.size()
, it gives
NullPointerException
.

Hope I have explained everything in detail.

Any advice would be really appreciated

Answer

Your VivzAdapter.java is returning null ,Because of what at the run time it throwing out the null pointer exception there.

    package com.portal.college.myapplication;

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.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by admin on 08-Feb-16.
 */
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder>{
    private final LayoutInflater inflater;
    List<Information> data = Collections.emptyList();

    public VivzAdapter(Context context,List<Information> data){
    inflater=LayoutInflater.from(context);
        this.data=data;
}
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }


    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
        holder.title.setText(current.title);
        holder.id.setImageResource(current.iconId);
    }

    @Override
    public int getItemCount() {

            return data.size();

    }
class MyViewHolder extends RecyclerView.ViewHolder{
    TextView title;
    ImageView id;

    public MyViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.listText);
        id = (ImageView) itemView.findViewById(R.id.listIcon);
    }
}
}

above code might solve the issue.