无法将java.util.HashMap类型的值转换为boolean

时间:2016-09-28 18:00:05

标签: 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 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;
    }





}

1 个答案:

答案 0 :(得分:0)

好的,所以你遇到的核心问题是Firebase正在返回一个Map,而不是一个布尔值。这是因为您配置了这种方式 - 每次添加子项时,您都会尝试查看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中,您不检查以确保传入的对象不为空。