Firebase数据库数据在读取时返回空值

时间:2016-12-24 04:22:02

标签: java android firebase

我不知道为什么,我已经探索了.setValue().updateChildren()方法,但无论出于什么原因,当我从firebase读取数据时,它返回null。以下是我写给Firebase的方式:

模型投票类:

@IgnoreExtraProperties
public class Poll {

private String question;
private String image_URL;

public Poll() {
}

public Poll(String Question, String Image_URL) {
    this.question = Question;
    this.image_URL = Image_URL;
}

public String getQuestion() {
    return question;
}

public void setQuestion(String question) {
    this.question = question;
}

public String getImage_URL() {
    return image_URL;
}

public void setImage_URL(String image_URL) {
    this.image_URL = image_URL;
}

@Exclude
public Map<String, Object> toMap(){
            HashMap<String, Object> result = new HashMap<>();
            result.put("question", question);
            result.put("image_URL", image_URL);
            return result;
     }

   }

*我使用.toMap()方法跟踪文档here并使用.updateChildren()

以下是我创建Firebase引用并写入数据库的位置:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);
    mStorage = FirebaseStorage.getInstance();
    mStorageRef = mStorage.getReferenceFromUrl("gs://firebase-fan-polls.appspot.com");


    mBaseRef = FirebaseDatabase.getInstance().getReference();
    mPollsRef = mBaseRef.child("Polls");
    mAddImageButton = (FloatingActionButton) findViewById(R.id.add_image_button);
    mAddAnswersButton = (ImageView) findViewById(R.id.add_answers_button);
    mImagePreview = (ImageView) findViewById(R.id.preview_image);
    mCreatePollQuestion = (EditText) findViewById(R.id.create_poll_question_editText);
    mCreatePollAnswerCounter = (TextView) findViewById(R.id.create_poll_answer_counter_TextView);
    mEditTextAnswerLayout = (ViewGroup) findViewById(R.id.create_poll_questions_answer_layout);
    mSubmitPollCreation = (FloatingActionButton) findViewById(R.id.submit_poll_FAB);
    mNumberOfPollAnswersCreatedByUser = 2;
    mAnswerChoices = new ArrayList<>();
    mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
    for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++) {
        createAnswerChoice(i + 1);
    }
    mAddAnswersButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mNumberOfPollAnswersCreatedByUser++;
            if (mNumberOfPollAnswersCreatedByUser > 5) {
                Toast.makeText(getApplicationContext(), R.string.max_create_answers, Toast.LENGTH_SHORT).show();
                return;
            }
            createAnswerChoice(mNumberOfPollAnswersCreatedByUser);
            mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
        }
    });

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

            //TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
            //check if image has been loaded first
            if (resultImageURL == null) {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_image_selected), Toast.LENGTH_LONG).show();
                return;
            }

            Poll poll = new Poll(mCreatePollQuestion.getText().toString(), resultImageURL);
            Map <String, Object> pollMap = poll.toMap();
            String key = mBaseRef.child("Polls").push().getKey();
            Map<String, Object> childUpdates = new HashMap<String, Object>();
            childUpdates.put("/Polls/" + key, pollMap);
            mBaseRef.updateChildren(childUpdates);


            if (mNumberOfPollAnswersCreatedByUser > 5) {
                Toast.makeText(getApplicationContext(), getResources().getText(R.string.poll_answers_greater_than_five), Toast.LENGTH_LONG).show();
                mNumberOfPollAnswersCreatedByUser = 5;
            }

            Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
            toHomeActivity.putExtra("viewpager_position", 2);
            startActivity(toHomeActivity);
        }
    });

所有内容都正确写入Firebase,因为我可以在控制台的数据库中看到它。我尝试从这个活动中读取它: 公共类PollFragment扩展Fragment {

@Bind(R.id.comment_label_counter)
TextView mCommentCounter;

@Bind(R.id.comments_label_icon)
ImageView mCommentsLabelIcon;

private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private DatabaseReference mSelectedPollRef;

private RadioGroup mPollQuestionRadioGroup;
private RadioGroup.LayoutParams mParams;

//static
private TextView mCommentsLabel;
private TextView mTotalVoteCounter;
private TextView mSelectedVote;
private TextView mYourVotelabel;
private ViewPager mViewPager;
private int mPagerCurrentPosition;
private static final String VOTE_COUNT_LABEL = "Vote_Count";
private static final String QUESTION_LABEL = "question";
private static final String ANSWERS_LABEL = "Answers";
private static final String POLL_LABEL = "Poll";
private static final String IMAGE_URL = "image_URL";

//all date items; dynamic
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private TextView mPollQuestion;
private ArrayList<RadioButton> mPollAnswerArrayList;
private HorizontalBarChart mPollResults;
ArrayList<BarEntry> pollResultChartValues;
private BarDataSet data;
private ArrayList<IBarDataSet> dataSets;
private ValueEventListener valueEventListener;
private String pollID;
private int mPollIndex;
private ProgressBar mProgressBar;

private OnFragmentInteractionListener mListener;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @return A new instance of fragment PollFragment.
 */
// TODO: Rename and change types and number of parameters
// TODO: Decide where to add comments button;
public static PollFragment newInstance(String pollIndex) {
    PollFragment fragment = new PollFragment();
    Bundle args = new Bundle();
    args.putString("POLL_ID", pollIndex);
    fragment.setArguments(args);
    return fragment;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //TODO: check navigation to see if there are different ID's being generated from trending, following, and new fragments
    Bundle args = getArguments();
    String pollID = args.getString("POLL_ID");
    Log.v("TAG", "THE PASSED ID Is " + pollID);
    mBaseRef = FirebaseDatabase.getInstance().getReference();
    mPollsRef = mBaseRef.child(POLL_LABEL);
    mSelectedPollRef = mPollsRef.child(pollID);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // TODO: Add Fragment Code to check if savedInstanceState == null; add at Activity Level?


    // Inflate the layout for this fragment
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_poll, container, false);
    ButterKnife.bind(this, rootView);
    getActivity().setTitle(R.string.todays_polls_title);

    //Initialize Poll Results Bar Chart and set to Invisible
    mPollResults = (HorizontalBarChart) rootView.findViewById(R.id.poll_results_chart);
    mPollResults.setBackgroundColor(getResources().getColor(R.color.white));
    mPollResults.setNoDataTextDescription(getResources().getString(R.string.no_results_description));
    mPollResults.setVisibility(View.INVISIBLE);

    mTotalVoteCounter = (TextView) rootView.findViewById(R.id.total_vote_counter);
    mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);
    mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);

    mProgressBar = (ProgressBar) rootView.findViewById(R.id.progress_bar_white);

    mPollQuestion = (TextView) rootView.findViewById(R.id.poll_question);
    mPollQuestion.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.poll_question_text_size));
    mPollQuestionRadioGroup = (RadioGroup) rootView.findViewById(R.id.poll_question_group);



    mSelectedPollRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Log.v("TAG", dataSnapshot.getKey());

            //add question
            String pollQuestion = (String) dataSnapshot.child(QUESTION_LABEL).getValue();
            Log.v("TAG", "THE POLL QUESTION IS " + pollQuestion);
            mPollQuestion.setText(pollQuestion);
            mPollQuestion.setTypeface(null, Typeface.BOLD);



            //add image
            String pollImageURL = (String) dataSnapshot.child(IMAGE_URL).getValue();
            Log.v("TAG", "THE POLL IMAGE URL IS" + pollImageURL);
            Picasso.with(getActivity())
                    .load(pollImageURL)
                    .fit()
                    .placeholder(R.drawable.loading_spinner_white)
                    .into((ImageView) rootView.findViewById(R.id.poll_image));

最后,这是我的Firebase数据库:

enter image description here

1 个答案:

答案 0 :(得分:0)

粗心的错误:

private static final String POLL_LABEL = "Poll";

应该是:

private static final String POLL_LABEL = "Polls";

第一个选择不是正确的Firebase引用,从而导致错误。