0

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

以下是主要活动的代码 - 问题是在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()被调用的回收观点适配器的代码。

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. 
+0

里面updateLogo显示你的大括号关闭;也许这是问题,所以请修复布局 – Aenadon

+0

我已经加倍检查,大括号没有关闭。如果情况确实如此,我认为程序不能运行以产生空例外。 @Aenadon –

+1

嗯没关系。你可以请尝试以下方法:在'String t = ...'上放置一个断点,然后看看c是否真的有一个值,然后使用IntelliJ的“评估表达式”评估调试器中的'r.getName();' – Aenadon

回答

0

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

相关问题