2016-12-24 15 views
0

なぜ、私は.setValue().updateChildren()の両方のメソッドを調べましたが、何らかの理由でfirebaseからデータを読み込むとnullが返されます。ここで私はFirebaseに書き込む方法です:Firebaseデータベースのデータ読み込み時にNullを返す

モデル投票クラス:

@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; 
    } 

    } 

私は.updateChildren()

の私の.toMap()方法や使用してドキュメントhereを、次の午前*私は私の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に正しく書かれています。私はこれをthで見ることができます私のコンソールにデータベースがあります。私が試してみて、この活動からそれを読む:

enter image description here

+0

データベース構造を置くことはできますか?また、 'mBaseRef'と' mSelectedPollRef'の初期化と 'QUESTION_LABEL'の値を教えてください – Wilik

+0

あなたのコードは私に紛らわしいものです。 poll.toMap()が何をしているのかわかりませんし、データベースが参照する場所を知ることもできません。また、なぜ単一のポーリングオブジェクトであると思われるものを書くために2つのマップが必要ですか?また、dataSnapshotの値をログに記録するとどうなりますか - あなたは何か期待していますか? –

+0

私の元の投稿ではっきりしないことをお詫びします。改訂されたコードをご覧ください。 – tccpg288

答えて

0

ケアレスミス:

private static final String POLL_LABEL = "Poll"; 

パブリッククラスPollFragmentがフラグメントを拡張{

@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データベースですする必要があります:

private static final String POLL_LABEL = "Polls"; 

最初の選択は正しいFirebaseを参照していないため、エラーが発生しました。

関連する問題