Android Firebase:应用程序在Click上崩溃

时间:2017-07-19 15:23:10

标签: android firebase firebase-realtime-database

我的应用程序运行正常。但是我在复制上添加onlicklistner后,每次点击刷新时我的应用程序都会崩溃。 这是我的代码。

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 个答案:

答案 0 :(得分:1)

int arraysize = storiesary.size();

如果storiesary为空,则可能导致NPE。目前你只在这里初始化

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

在调用setStory()之前可能无法执行。

考虑在onCreateView中初始化它,以确保它不为空。