java.lang.IllegalStateException:片段未附加到上下文。 Firebase数据库

时间:2019-03-22 16:50:16

标签: java android firebase-realtime-database textview illegalstateexception

为什么将Firebase数据库中的数据更新到活动片段中的特定textview时会崩溃? 我的代码也没错。请帮忙。当我在线检查时,所有解决方案都不明确,并且已经过时。有人可以告诉我我该怎么做吗?

public class WinOrDraw extends Fragment {

private TextView time_match, team_results, c_time;
private ImageView result_colour;

public WinOrDraw() {
    // Required empty public constructor
}


@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_win_or_draw, container, false);

    resultRef = FirebaseDatabase.getInstance().getReference().child("Win Or Draw One");

    time_match = view.findViewById(R.id.time);
    team_results = view.findViewById(R.id.result_teams);
    result_colour = view.findViewById(R.id.resulting_image);



    resultRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String time_string = Objects.requireNonNull(dataSnapshot.child("time").getValue()).toString();
            String team_results_string = Objects.requireNonNull(dataSnapshot.child("team_result").getValue()).toString();
            String final_colour = Objects.requireNonNull(dataSnapshot.child("result_colour").getValue()).toString();

            time_match.setText(time_string);
            team_results.setText(team_results_string);

            switch (final_colour) {
                case "won":
                    result_colour.setImageDrawable(getResources().getDrawable(R.drawable.checked));
                    break;
                case "lost":
                    result_colour.setImageDrawable(getResources().getDrawable(R.drawable.unchecked));
                    break;
                case "undecided":
                    result_colour.setImageDrawable(getResources().getDrawable(R.drawable.pause));
                    break;
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

    return view;
}

}

这里是日志

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.softwaremongul.supertips, PID: 27762
java.lang.IllegalStateException: Fragment WINorDraw{7069d0d} not attached to a context.
    at android.support.v4.app.Fragment.requireContext(Fragment.java:696)
    at android.support.v4.app.Fragment.getResources(Fragment.java:760)
    at com.softwaremongul.supertips.BETOFTHEDAY$5.onDataChange(WINorDraw.java:134)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.6:75)

请帮助。

0 个答案:

没有答案