【问题标题】:Failed to convert value of type java.util.HashMap to boolean无法将 java.util.HashMap 类型的值转换为布尔值
【发布时间】:2016-09-28 18:00:05
【问题描述】:

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

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





}

【问题讨论】:

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

标签: android firebase firebase-realtime-database


【解决方案1】:

好的,所以您遇到的核心问题是 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 中,您无需检查以确保传入的对象不为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多