【问题标题】:Android If statement not being accessed for some reason [duplicate]由于某种原因未访问Android If语句[重复]
【发布时间】:2016-12-26 18:18:57
【问题描述】:

我需要你的帮助 我正在Android上构建这个应用程序,我遇到了这个问题,其中一个字符串数据从Firebase数据库中检索并分配给一个字符串值,当我尝试使用(IF)语句来使用内部条件时,我得到的只是编译器检查值条件,从不进入语句。 我使用调试模式检查正在运行的应用程序,存储到字符串中的值是正确的,如果语句没有问题。

我在有问题的地方添加了部分代码

myRef.addValueEventListener(new ValueEventListener() {
        public static final String TAG = "Testtttttttt";

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " + value);
            if (value == "START") {
                textView.setText(value);


            }
        }

【问题讨论】:

  • 使用 value.equals("START") 代替 value == "START"
  • 请遵循通常发布在 Java Oracle 页面上的标准。字符串比较应始终使用 stringVar.equals() 方法

标签: android if-statement firebase firebase-realtime-database try-catch


【解决方案1】:

使用

value.equals("START")

按值比较字符串是否相等。

== 通过引用检查相等性,在您的情况下这始终是错误的。

阅读http://www.javatpoint.com/string-comparison-in-java了解更多信息。

【讨论】:

    【解决方案2】:

    你应该使用:

    myRef.addValueEventListener(new ValueEventListener() {
        public static final String TAG = "Testtttttttt";
    
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " + value);
            // correct compare string1.equals(string2)
            if (value.equals("START")) { // You cant compare string1 == string2
                textView.setText(value);
    
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多