2017-07-19 185 views
0

我的應用程序運行良好。但是,當我在副本上添加onlicklistner後,每次點擊刷新時,我的應用程序都會崩潰。 這是我的代碼。Android Firebase:應用程序崩潰點擊

public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) { 
    this.localView = paramLayoutInflater.inflate(R.layout.fragmenthome, paramViewGroup, false); 
    story = (TextView) localView.findViewById(R.id.story_text); 
    rl = (RelativeLayout) localView.findViewById(R.id.rlLayout); 
    linearLayout = (LinearLayout) localView.findViewById(R.id.bottom_bar); 
    imgCopy = (ImageView) localView.findViewById(R.id.copyStory); 
    imgRefresh = (ImageView) localView.findViewById(R.id.refreshStory); 


    databaseReference = FirebaseDatabase.getInstance().getReference().child("stories"); 

    databaseReference.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      storiesary = new ArrayList<String>(); 
      for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) { 
       HashMap map =(HashMap) childSnapshot.getValue(); 
       if(map!=null) { 
        storiesary.add((String) map.get("storytext")); 
       } 
      } 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 
      Log.d(TAG,"check your internet connection and try again"); 
     } 
    }); 


    imgRefresh.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      setStory(); 
     } 
    }); 

    imgCopy.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      String copy = story.getText().toString(); 

      ClipboardManager clipboard = (ClipboardManager) FragmentHome.this.getActivity().getSystemService(FragmentHome.this.getActivity().CLIPBOARD_SERVICE); 
      ClipData clip = ClipData.newPlainText("cpy_quotes", copy); 
      clipboard.setPrimaryClip(clip); 
      Toast.makeText(FragmentHome.this.getActivity(), "Text Copied to clipboard.", 0).show(); 
     } 
    }); 
    return localView; 

} 

public void setStory() 
{ 
    int arraysize = storiesary.size(); 
    final int arrayposition1 = (new Random()).nextInt(arraysize); 
    story.setText(storiesary.get(arrayposition1)); 
} 

而且這是在我上刷新

Android monitor

單擊如果我刪除代碼複製,然後應用程序被運行完美我所得到。

回答

1
int arraysize = storiesary.size(); 

如果storiesary爲空,這會導致NPE。目前你只在這裏初始化它

@Override 
public void onDataChange(DataSnapshot dataSnapshot) { 
    storiesary = new ArrayList<String>(); 

setStory()調用之前可能不會被執行。

考慮在onCreateView中初始化它,以確保它不爲null。

+0

問題已解決..謝謝你 –

+0

@DalsukhTapaniya接受答案 –