62854

Firebase android error “Failed to convert value of type ”

Question:

This code is crashing on start;

<blockquote>

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.manya.eventspage, PID: 2974 com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String at com.google.android.gms.internal.zzamy.zzcg(Unknown Source) at com.google.android.gms.internal.zzamy.zzb(Unknown Source) at com.google.android.gms.internal.zzamy.zza(Unknown Source) at com.google.firebase.database.DataSnapshot.getValue(Unknown Source) at com.example.manya.eventspage.Events$1.onDataChange(Events.java:46) at com.google.android.gms.internal.zzajp.zza(Unknown Source) at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source) at com.google.android.gms.internal.zzaks$1.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

</blockquote>

<strong><em>the code is</em></strong>

package com.example.manya.eventspage; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.text.*; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Events extends AppCompatActivity { private TextView t; private static ListView l; private static ArrayAdapter<String> adapter; final static ArrayList<String> arrayList = new ArrayList<String>(); FirebaseDatabase database=FirebaseDatabase.getInstance(); protected DatabaseReference myRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_events); t = (TextView) findViewById(R.id.textView3); l = (ListView) findViewById(R.id.list_view); myRef=database.getReference().child("events"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String val=dataSnapshot.child("events").getValue(String.class); arrayList.add(val); } @Override public void onCancelled(DatabaseError databaseError) { } }); // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown), // and the array that contains the data adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList); l.setAdapter(adapter); } protected void onResume() { super.onResume(); Intent in=getIntent(); if(in.hasExtra(Intent.EXTRA_TEXT)) { String d=in.getStringExtra(Intent.EXTRA_TEXT); final DatabaseReference postsRef = database.getReference().child("events"); DatabaseReference newPostRef = postsRef.push(); newPostRef.setValue(new event(d)); arrayList.add(d); // next thing you have to do is check if your adapter has changed adapter.notifyDataSetChanged(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.add_event) { Context context=Events.this; Class destclass=addevent.class; Intent str=new Intent(context,destclass); startActivity(str); return true; } return super.onOptionsItemSelected(item); }

The json data is

{ "events" : { "events" : { "-KkfUKAYAriWN7NYqTcx" : { "event_detail" : "21 05 2017, 20:20TextView" } } } }

Answer1:

Your code fails to take care of the fact that you have a list of events under /events/events. To handle this correctly you have two approaches:

<ol><li>Use a ValueEventListener and loop over the child nodes</li> <li>Use a ChildEventListener</li> </ol>

The first is closest to your current code and just adds an extra loop:

myRef=database.getReference().child("events/events"); // note the change in path myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) { String val=childSnapshot.getValue(String.class); arrayList.add(val); } } @Override public void onCancelled(DatabaseError databaseError) { throw databaseError.toException(); // don't ignore errors } });

The second approach tells Firebase to handle the list in its SDK and surfaces each child:

myRef=database.getReference().child("events/events"); // note the change in path myRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) { String val=dataSnapshot.getValue(String.class); arrayList.add(val); } ... });

Recommend

  • GoogleMaps.oncameraChangedListener is never called
  • Unity Android with AppCompat Rejecting re-init on previously-failed class java.lang.Class
  • Open Fragment From Activity
  • AdMob - Ad not displayed - Error 2
  • How can I speed up this row-by-row operation in data.table
  • Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.goog
  • Firebase - retrieve data in Android
  • How to mock current date?
  • Found com.google.android.gms:play-services-places:9.2.1, but version 9.0.2 is needed for the google-
  • Is it possible to disable certain weekdays in DatePickerDialog?
  • How to get month name with year and list of years between two Date
  • Send data from edittext to listview
  • How can go in last activity with resume button?
  • How to get listview position?
  • Find Previous month name using Calender or any classes that in java
  • Elasticsearch script query involving root and nested values
  • Why use database factory in asp.net mvc?
  • How do I configure context broker accept post requests from my remote sensor?
  • Android application: how to use the camera and grab the image bytes?
  • Connect .sks to skscene.h
  • Hardware Accelerated Image Scaling in windows using C++
  • How to test if a URL from an Eclipse bundle is a directory?
  • Dialing with Intent.ACTION_CALL stopps at # in phone number
  • Javascript Callbacks with Object constructor
  • MySQL WHERE-condition in procedure ignored
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • Can I make an Android app that runs a web view in Chrome 39?
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Web-crawler for facebook in python
  • Cannot Parse HTML Data Using Android / JSOUP
  • How to include full .NET prerequisite for Wix Burn installer
  • trying to dynamically update Highchart column chart but series undefined
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Getting Messege Twice Using IMvxMessenger
  • Turn off referential integrity in Derby? is it possible?
  • Add sale price programmatically to product variations
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal
  • How to load view controller without button in storyboard?
  • How do I use LINQ to get all the Items that have a particular SubItem?