从firebase检索数据但在尝试使用检索到的数据时获取空指针异常

时间:2017-06-15 20:28:49

标签: android nullpointerexception android-recyclerview substring

我在Recyclerview中显示了从Firebase数据库中检索到的图像。我正在尝试实现字母索引,以便当我单击一个字母时,将检索图像的名称。然后我应用子字符串来获取名称的第一个字符,使用equals()检查字符是否等于单击的字母,如果不相等则从回收器视图中删除该项。问题是当我应用子字符串时会产生空指针异常。我知道我成功检索了图像的名称,因为我可以使用Toast在屏幕上显示它。当我尝试获取子字符串时,我不知道是什么原因导致空指针异常。任何帮助将不胜感激。

以下是主要活动的代码 - 问题出在updateLogoDisplay():

public class AddBrandPage extends AppCompatActivity implements OnClickListener {

    //declare variables
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
    private RecyclerView alpharecyclerView;
    private RecyclerView.LayoutManager alphaLayoutManager;
    private RecyclerView.Adapter alphaAdapter;
    private DatabaseReference myRef;
    private DatabaseReference userRef;
    private Button btn_skip;
    private Button btn_save;
    private CheckBox checkbox;
    private FirebaseAuth mAuth;
    private String t;

    List<LogoItems> brandLogo = new ArrayList<>();
    //HashMap<String, String> saveBrands = new HashMap<>();
    List<LogoItems> removedBrandLogo = new ArrayList<>();
    List<String> selectionList = new ArrayList<>();
    List<AlphaItems> alphaList = new LinkedList<>();


     String [] alphabets = {"All","A","B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_brand_page);

        //initialize variables
        btn_skip = (Button) findViewById(R.id.btn_skip);
        btn_save = (Button) findViewById(R.id.btn_save);
        myRef = FirebaseDatabase.getInstance().getReference().child("/brands");
        userRef = FirebaseDatabase.getInstance().getReference().child("/users");
        // checkbox = (CheckBox) findViewById(R.id.checkbox);

        //calls to load data to arraylists
        //alpha = getResources().getStringArray(alphabets);

        loadAlpha();
        loadLogoImgData();


        //set the listener for the buttons click event
        btn_skip.setOnClickListener(this);
        btn_save.setOnClickListener(this);


    }

    private void loadAlpha() {

        for (String alpha: alphabets) {
            alphaList.add(new AlphaItems(alpha));

        }
        startAlphaRecyclerView();

    }

    public void loadLogoImgData() {

        brandLogo.clear();
        myRef.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()) {
                    LogoItems value = brandSnapshot.getValue(LogoItems.class);
                    brandLogo.add(value);
                }
                startLogoRecyclerView();
            }


            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }


    @Override
    public void onClick(View view) {

        if (view == btn_skip) {
            //if skip button clicked close current window and go to user main page
            finish();
            startActivity(new Intent(getApplicationContext(), UserMainPage.class));

        }
        if (view == btn_save) {
            //selector.addAll(logoadapter.selector);
            saveData();
        }

    }


    public void startLogoRecyclerView() {
        // set the main recyclerview view for the logo in the layout
        recyclerView = (RecyclerView) findViewById(R.id.recylView);
        recyclerView.setHasFixedSize(true);

        // set the main layoutManager of the recyclerview
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        // set the recycler view adapter
        adapter = new LogoAdapter(brandLogo, getBaseContext(), AddBrandPage.this);
        recyclerView.setAdapter(adapter);

    }

    public void startAlphaRecyclerView() {
        // set the main recyclerview view for the logo in the layout
        alpharecyclerView = (RecyclerView) findViewById(R.id.alpharecyclerView);
        alpharecyclerView.setHasFixedSize(true);

        // set the main layoutManager of the recyclerview
        alphaLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        alpharecyclerView.setLayoutManager(alphaLayoutManager);

        // set the recycler view adapter
        alphaAdapter = new AlphaAdapter(alphaList, getBaseContext(), AddBrandPage.this);
        alpharecyclerView.setAdapter(alphaAdapter);

    }



    public List<String> prepareSelection(View v, int position) {

        checkbox = (CheckBox) v;

        //check if user selected checkbox and add or remove from list
        //if (checkbox.isChecked()) {
        selectionList.add(brandLogo.get(position).getName());

        //} else {
        // selectionList.remove(brandLogo.get(position).getLogo());

        //}
        return selectionList;
    }



    public void updateLogoDisplay(String letter) {

        if (!(letter.equals("All"))) {
            //Iterator<LogoItems> iter = brandLogo.iterator();

            for (Iterator<LogoItems> iter = brandLogo.iterator(); iter.hasNext();){
            //while (iter.hasNext()) {
                LogoItems r = iter.next();
                String c = r.getName();
                String t = c.substring(0,1);
                if (c != null){
                    if (letter.equals(t)) {


                    //brandLogo.remove(r);
                    removedBrandLogo.add(r);
                    iter.remove();

                }
                }else {
                }
            }
            brandLogo.removeAll(removedBrandLogo);
            adapter.notifyDataSetChanged();
        }

    }


    public void saveData() {

        final FirebaseAuth mAuth;
        final DatabaseReference userRef;

        mAuth = FirebaseAuth.getInstance();
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        DatabaseReference curUser = userRef.child(mAuth.getCurrentUser().getUid());
        curUser.child("brands").setValue(selectionList);//save selected items to the database

    }

}

以下是从中调用updateLogoDisplay()的recycler视图适配器的代码。

public class AlphaAdapter extends RecyclerView.Adapter<AlphaAdapter.AlphaViewHolder> {

    //declare variables
    List<AlphaItems> alphaList = new ArrayList<>();
    private AddBrandPage addBrandPage;
    private Context context;


    //the constructor
    public AlphaAdapter (List<AlphaItems> alphaList, Context context, AddBrandPage addBrandPage){
        this.alphaList = alphaList;
        this.context = context;
        this.addBrandPage = addBrandPage;

    }


    @Override
    public AlphaAdapter.AlphaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.alpha_items, parent, false);
        AlphaViewHolder alphaViewHolder = new AlphaViewHolder(view,addBrandPage);
        return alphaViewHolder;
    }

    @Override
    public void onBindViewHolder(AlphaAdapter.AlphaViewHolder holder, int position) {
        holder.txt_alpha.setText(alphaList.get(position).getLetter());
    }

    @Override
    public int getItemCount() {
        return alphaList.size();
    }

    public class AlphaViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        //declare variables
        private TextView txt_alpha;
        private AddBrandPage addBrandPage;


        //the constructor
        public AlphaViewHolder (View itemView, AddBrandPage addBrandPage){
            super(itemView);
            this.addBrandPage = addBrandPage;

            //initialize variables
            txt_alpha = (TextView) itemView.findViewById(R.id.txt_alpha);

            //set click listener
            txt_alpha.setOnClickListener(this);


        }


        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            String letter = alphaList.get(position).toString();
            addBrandPage.updateLogoDisplay(letter);

        }
    }
}

这是logcat错误:

06-15 15:42:10.306 30577-30577/com.test.test D/AndroidRuntime: Shutting down VM
06-15 15:42:10.307 30577-30577/com.test.test E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.test.test, PID: 30577
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.substring(int)' on a null object reference
                                                                     at com.test.test.AddBrandPage.updateLogoDisplay(AddBrandPage.java:253)
                                                                     at com.test.test.AlphaAdapter$AlphaViewHolder.onClick(AlphaAdapter.java:78)
                                                                     at android.view.View.performClick(View.java:5637)
                                                                     at android.view.View$PerformClick.run(View.java:22429)
                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
06-15 15:46:57.570 30577-30626/com.test.test W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

1 个答案:

答案 0 :(得分:0)

我能够解决问题。当迭代到达结束时,变量c变为空。这就是产生空指针异常的原因。为了避免null错误,我在String t = ... line之前添加了if(c!= null)。