Android 未能将java.util.HashMap类型的值转换为布尔值

Android 未能将java.util.HashMap类型的值转换为布尔值,android,firebase,firebase-realtime-database,Android,Firebase,Firebase Realtime Database,我正在尝试检测我的应用程序的连接状态,但这是我面临的错误: Failed to convert value of type java.util.HashMap to boolean 我用的是Firebase。错误在线: boolean connected = dataSnapshot.getValue(Boolean.class); 因此,错误出现在OnDataFinishedLoading方法中。起初数据是来的,但现在我只想检测应用程序的网络连接。下面是我的代码: public class

我正在尝试检测我的应用程序的连接状态,但这是我面临的错误:

Failed to convert value of type java.util.HashMap to boolean
我用的是Firebase。错误在线:

boolean connected = dataSnapshot.getValue(Boolean.class);
因此,错误出现在OnDataFinishedLoading方法中。起初数据是来的,但现在我只想检测应用程序的网络连接。下面是我的代码:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {



    public static String KEY_HEADLINES="headlines";
    public static String KEY_DETAILS="details";


   // private static final String TAG = "Ask Doctor App";

    ProgressBar pb;


   public  List<NewsModel> newslist;

   public NewsAdapter2 adapter;
    private RecyclerView mRecyclerView;

    private DatabaseReference mRef;
    ImageView image_news;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // call the array list
        newslist = new ArrayList<NewsModel>();

        pb = (ProgressBar) findViewById(R.id.progressBarNews);
        image_news =(ImageView) findViewById(R.id.image_news);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
       mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //Enabling offline capabilities
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

         // firebase initialisation......
        mRef =  FirebaseDatabase.getInstance().getReference("News");
        // keep my data synced
        mRef.keepSynced(true);

        OnDataFinishedLoading();





        // load data

        //declare the toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



     //   ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //NetworkInfo netInfo = cm.getActiveNetworkInfo();










        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              /*  if (isOnline()) {

                    Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
                            .setAction("Thanks.", null).show();
                } else {
                    Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
                            .setAction("", null).show();

                }

                Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
                        .setAction("Thanks.", null).show();*/
            }
        });














        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);




    }



private void OnDataFinishedLoading(){

    mRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            boolean connected = dataSnapshot.getValue(Boolean.class);
            if(connected) {

                pb.setVisibility(View.INVISIBLE);
                LoadData(dataSnapshot);

            } else{
               Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();

            }

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            LoadData(dataSnapshot);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


}

    public void LoadData (DataSnapshot dataSnapshot){




        System.out.println(dataSnapshot.getValue());

        NewsModel news_model =dataSnapshot.getValue(NewsModel.class);


        newslist.add(news_model);

        adapter = new NewsAdapter2(MainActivity.this, newslist);
        mRecyclerView.setAdapter(adapter);




    }

   /* protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }
    }
*/




    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/

  /*  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Intent i;
        if (id == R.id.hospitals) {

            i = new Intent(MainActivity.this, HealthCentres.class);
            startActivity(i);


        } else if (id == R.id.doctors) {

            i = new Intent(MainActivity.this, Doctors.class);
            startActivity(i);


        } /*else if (id == R.id.location) {
            i = new Intent(MainActivity.this, Location.class);
            startActivity(i);

        } */else if (id == R.id.tips) {
            i = new Intent(MainActivity.this, Tips.class);
            startActivity(i);

        } /*else if (id == R.id.faq) {


        }
        */
        /*
        else if (id == R.id.suggestions) {

        }
        */
        else if (id == R.id.contacts) {
            i= new Intent(MainActivity.this, ContactUs.class);
            startActivity(i);

        }
        /*
        else if (id == R.id.settings) {

        }
        */
        else if (id == R.id.about) {
            i = new Intent(MainActivity.this, AboutUs.class);
            startActivity(i);

        }





        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }





}

好的,你遇到的核心问题是Firebase返回的是一个映射,而不是布尔值。这是因为每次添加子对象时,您都会尝试查看DataSnapshot,这是您设置的侦听器所做的,并尝试获取布尔值。但是,快照是添加到数据库中的子项,而不是布尔值,因此您可以得到一个映射

如果您只想验证是否成功添加了子级,我将执行以下操作:

    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

       Object value = dataSnapshot.getValue();

       if(value != null) {
            pb.setVisibility(View.INVISIBLE);
            LoadData(dataSnapshot);
        } else{
           Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
        }
    }

然而,这并不能真正解决您的网络连接问题。只要在firebase对象中添加一个非空的子对象,它就会执行一些操作,这可能会经常发生。此外,在LoadData中,您不必检查以确保传入的对象不为空。

错误消息中有什么您不清楚的地方?我发布的错误,我如何解决它在@Tunaki中仍然是新的请发布数据库结构,最好是JSON格式,而不是控制台的屏幕截图,还有mRef初始化。我已经更新了我的代码@Wiliki