Firebase数据库数据在读取时返回空值 [英] Firebase Database Data Returning Null When Reading
问题描述
我不知道为什么,我已经探索了 .setValue()
和 .updateChildren()
方法,但无论什么原因,当我从Firebase读取数据时,它将返回null。以下是我写给Firebase的信息:
模型民意调查班:
@IgnoreExtraProperties
方法和使用
public class Poll {
private String question;
私人字符串image_URL;
$ b $ 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(问题,问题);
result.put(image_URL,image_URL);
返回结果;
$ b $ / code $ / pre
$ b我是按照文档< here .toMap().updateChildren()
这里是我创建我的Firebase引用并写入数据库:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $保护无效的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 ();
return;
}
createAnswerChoice() mNumberOfPollAnswersCreatedByUser);
mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
}
});
mSubmitPollCreation.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
// TODO:Need检查是否添加投票要求,即问题,答案,......
//检查图像是否已经被加载
if(resultImageURL == null){
Toast。 makeText(getApplicationContext(),getResources().getString(R.string.no_image_selected),Toast.LENGTH_LONG).show();
return;
}
轮询轮询= new Poll(mCreatePollQuestion.getText()。toString(),resultImageURL);
Map< String,Object> pollMap = poll.toMap();
String key = mBaseRef.child(Polls) ();
MapUp< String,Object> childUpdates = new HashMap< String,Object>();
childUpdates.put(/ Polls /+ key,pollMap);
mBaseRef.updateChildren(childUpdates );
$ b if(mNumberOfPollAnswersCreatedByUser> 5){
Toast.makeText(getApplicationContext(),getResources().getText(R.string.poll_answers_greater_than_five),Toast.LENGTH_LONG)显示();
mNumberOfPollAnswersCreatedByUser = 5;
}
Intent toHomeActivity = new Intent(CreateActivity.this,HomeActivity.class);
toHomeActivity.putExtra(viewpager_position,2);
startActivity(toHomeActivity);
}
});
所有内容都正确写入到Firebase中,正如我在控制台的数据库中看到的一样。我尝试从这个活动中读取它:
public class PollFragment extends 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;
私人RadioGroup mPollQuestionRadioGroup;
私人RadioGroup.LayoutParams mParams;
//静态
私有TextView mCommentsLabel;
私人TextView mTotalVoteCounter;
私人TextView mSelectedVote;
私人TextView mYourVotelabel;
私人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;
//所有日期项目;动态
私人DateFormat mDateFormat;
私人日期mDate;
private String mCurrentDateString;
私人TextView mPollQuestion;
private ArrayList< RadioButton> mPollAnswerArrayList;
private HorizontalBarChart mPollResults;
ArrayList< BarEntry> pollResultChartValues;
私人BarDataSet数据;
private ArrayList< IBarDataSet>数据集;
private ValueEventListener valueEventListener;
私人字符串pollID;
private int mPollIndex;
私人ProgressBar mProgressBar;
private OnFragmentInteractionListener mListener;
$ b $ public PollFragment(){
//必需的空公共构造函数
$ b $ **
*使用此工厂方法创建
*这个片段的新实例使用提供的参数。
*
* @return片段PollFragment的新实例。
* /
// TODO:重命名并更改参数的类型和数量
// TODO:决定添加注释按钮的位置;
public static PollFragment newInstance(String pollIndex){
PollFragment fragment = new PollFragment();
Bundle args = new Bundle();
args.putString(POLL_ID,pollIndex);
fragment.setArguments(args);
return fragment;
$ b @Override
public void onCreate(Bundled savedInstanceState){
super.onCreate(savedInstanceState);
// TODO:检查导航,看看是否有不同的ID从趋势,跟随和新的片段生成
Bundle args = getArguments();
String pollID = args.getString(POLL_ID);
Log.v(TAG,PASSED ID is+ pollID);
mBaseRef = FirebaseDatabase.getInstance()。getReference();
mPollsRef = mBaseRef.child(POLL_LABEL);
mSelectedPollRef = mPollsRef.child(pollID);
$ b @Override
public view onCreateView(LayoutInflater inflater,ViewGroup container,
Bundled savedInstanceState){
// TODO:Add片段代码来检查savedInstanceState == null;在活动级别添加?
//膨胀这个片段的布局
final ViewGroup rootView =(ViewGroup)inflater.inflate(R.layout.fragment_poll,container,false);
ButterKnife.bind(this,rootView);
getActivity()。setTitle(R.string.todays_polls_title);
//初始化轮询结果条形图并设置为不可见
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);
$ b mSelectedPollRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
Log.v(TAG,dataSnapshot.getKey());
//添加问题
字符串pollQuestion =(String)dataSnapshot.child(QUESTION_LABEL).getValue();
Log.v(TAG,POLL QUESTION IS+ pollQuestion);
mPollQuestion.setText(pollQuestion);
mPollQuestion.setTypeface(null,Typeface.BOLD);
$ b //添加图片
字符串pollImageURL =(String)dataSnapshot.child(IMAGE_URL).getValue();
Log.v(TAG, poll image image URL+ pollImageURL);
Picasso.with(getActivity())
.load(pollImageURL)
.fit()
.placeholder(R.drawable .loading_spinner_white)
。((ImageView)rootView.findViewById(R.id.poll_image));
最后,这是我的Firebase数据库:
不小心的错误:
private static final String POLL_LABEL =Poll;
应该是:
private static final String POLL_LABEL =Polls;
第一个选择不是正确的Firebase引用,从而导致错误。 b
I am not sure why, I have explored both .setValue()
and .updateChildren()
methods, but for whatever reason when I read data from firebase it is returning null. Here is how I write to Firebase:
Model Poll Class:
@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;
}
}
*I am following the documentation here with my .toMap()
method and use of .updateChildren()
Here is where I create my Firebase references and write to the database:
@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);
}
});
Everything is writing to Firebase correctly, as I can see it in the database in my console. I try and read it from this activity: public class PollFragment extends 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));
Finally, here is my Firebase Database:
Careless mistake:
private static final String POLL_LABEL = "Poll";
Should be:
private static final String POLL_LABEL = "Polls";
The first choice was not the correct Firebase referencing thus causing the error.
这篇关于Firebase数据库数据在读取时返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!