java.lang.NullPointerException:com.firebase.ui.database.FirebaseRecyclerAdapter.startListening()'对空对象的引用

时间:2018-09-08 10:49:07

标签: android firebase android-recyclerview adapter

我从Firebase数据库检索了数据,并希望使用FirebaseAdapter在回收器视图中显示数据。当我使用adapter.startListening()方法时,它显示跟随错误,当我删除它时,它可以正常工作,但不加载任何内容

这是我尝试过的:

package com.andisofttechnology.myapplication.Model;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.app.AppCompatActivity;
        import android.support.design.widget.FloatingActionButton;
        import android.support.design.widget.Snackbar;
        import android.support.v7.widget.LinearLayoutManager;
        import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
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;
        import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
        import android.widget.Toast;
        import com.andisofttechnology.myapplication.Common.Common;
        import com.andisofttechnology.myapplication.Interface.ItemClickListener;
        import com.andisofttechnology.myapplication.R;
        import com.andisofttechnology.myapplication.ViewHolder.MenuViewHolder;

        import com.firebase.ui.database.FirebaseRecyclerAdapter;
        import com.firebase.ui.database.FirebaseRecyclerOptions;
        import com.google.firebase.database.DatabaseReference;
        import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;

import java.util.Locale;


public class Home extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
TextView menu_name;
LinearLayoutManager layoutManager;
   /* FirebaseRecyclerAdapter<Category,MenuViewHolder> firebaseRecyclerAdapter;*/
private TextView txtMenuName;
FirebaseRecyclerAdapter<Category,MenuViewHolder> firebaseRecyclerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);





        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Menu");
        setSupportActionBar(toolbar);
        //Init Firebase
        database = FirebaseDatabase.getInstance();
        category = database.getReference("Category");




        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();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        //Set Name for User
        View headerView = navigationView.getHeaderView(0);
        txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
        txtFullName.setText(Common.currentUser.getName());


        //Load Menu

        recycler_menu = (RecyclerView)findViewById(R.id.recycler_menu);
        recycler_menu.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recycler_menu.setLayoutManager(layoutManager);
        layoutManager = new LinearLayoutManager(this);
        loadMenu();
    }


private void loadMenu() {
             Query query = FirebaseDatabase.getInstance()
                     .getReference()
                     .child("Category");

        FirebaseRecyclerOptions<Category> options =
                new FirebaseRecyclerOptions.Builder<Category>()
                        .setQuery(query, Category.class)
                        .build();


       FirebaseRecyclerAdapter firebaseRecyclerAdapter = new  FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {

            @Override
            public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.menu_item, parent, false);
                return new MenuViewHolder(view);

            }


            @Override
            protected void onBindViewHolder(MenuViewHolder holder, int position, Category model) {
              txtMenuName = (TextView)findViewById(R.id.menu_name);
                holder.txtMenuName.setText(model.getName());
              /*  Picasso
                        .with(getBaseContext())
                        .load(<model.getName()>)
                       .resize(2048, 1600)
                        .onlyScaleDown() // the image will only be resized if it's bigger than 2048x 1600 pixels.
                        .into(<ImageView>);*/
                Picasso.with(getBaseContext()).load(model.getName()).into(holder.imageView);
                final Category clickItem = model;
                holder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        Toast.makeText(Home.this, ""+clickItem.getName(),Toast.LENGTH_SHORT).show();

                    }
                });
            }


        };
       /*firebaseRecyclerAdapter.startListening();*/
        recycler_menu.setAdapter(firebaseRecyclerAdapter);
     /*   firebaseRecyclerAdapter.stopListening();*/



    }

    @Override
    public void onStart() {
        super.onStart();
        firebaseRecyclerAdapter.startListening();
    }
    @Override
    public void onStop(){
        super.onStop();
        firebaseRecyclerAdapter.startListening();
    }



    @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.home, 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);
    }

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

     /*   if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }*/

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

MenuViewHolder.class

package com.andisofttechnology.myapplication.ViewHolder;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.andisofttechnology.myapplication.Interface.ItemClickListener;
import com.andisofttechnology.myapplication.R;

/**
 * Created by fullfocus on 9/6/2018.
 */

public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView txtMenuName;
    public ImageView imageView;
    private  ItemClickListener itemClickListener;
    public MenuViewHolder(View itemView) {
        super(itemView);
        txtMenuName = (TextView)itemView.findViewById(R.id.menu_name);
        imageView = (ImageView)itemView.findViewById(R.id.menu_image);
        itemView.setOnClickListener(this);
    }
    public void setItemClickListener(ItemClickListener itemClickListener){
       this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View view) {
        itemClickListener.onClick(view,getAdapterPosition(),false);

    }
}

我已经阅读了与此相关的问题,但找不到适合我的解决方案。有人可以告诉我错误是什么吗?

1 个答案:

答案 0 :(得分:1)

要解决此问题,请更改以下代码行:

FirebaseRecyclerAdapter firebaseRecyclerAdapter = new  FirebaseRecyclerAdapter<Category, MenuViewHolder>(options)

firebaseRecyclerAdapter = new  FirebaseRecyclerAdapter<Category, MenuViewHolder>(options)

您已经将变量firebaseRecyclerAdapter设置为全局变量。