【问题标题】:Global variable value not being updated in time全局变量值没有及时更新
【发布时间】:2014-08-06 15:30:41
【问题描述】:

所以我在 android 中有一个 textview 并使用 xml 设置了 onclicklistener

<TextView
    android:id="@+id/usernameView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:onClick="userNameClicked"
    android:clickable="true"/>

在我的“userNameClicked”方法中

String usernamePointsDialog = "ITSSTILLNULL"; // this is the global variable that doesn't update until clicked a second time

    public void userNameClicked(View v) {

    global_position = postsView.getPositionForView(v);


    Log.i(TAG, "value" + global_position);

    int global_position2 = global_position - 1;

    String userObjectId2 = posts.getItem(global_position2).getUserString();

    Log.i(TAG, "value" + userObjectId2);

    // code that queries the database here
    {
    String userPointsFromDatabase = String.valueOf(userPoints2.getInt("userPoints"));
    // this is the code that returns the correct value but doesn't update the GV in    time

    Log.i(TAG, "value" + userPointsFromDatabase);

    usernamePointsDialog = userPointsFromDatabase;

    Log.i(TAG, "value" + userPointsFromDatabase);

    Log.i(TAG, "value1" + usernamePointsDialog);

    }

   }

});
        createDialog2().show();

   // this creates a dialog box that shows username (which is always the correct value, and the second value which always lags behind by one).

}

所以我可以点击的用户名显示在列表视图中,除了全局变量 usernamePointsDialog 的值落后一之外,所有代码都可以正常工作,所以如果我点击用户名,则会弹出正确的用户名,但值对数据库的查询显示“ITSSTILLNULL”,直到第二次单击它显示正确的值。所有日志都表明正在从数据库中查询正确的值,只是全局变量没有及时更新,createdialog2 方法将(用户名点对话框)全局变量显示为正确的值。

由于各种原因,我无法使用最终标记/局部变量,并且不确定如何解决此问题。非常感谢您提供的任何帮助!

【问题讨论】:

  • 代码显示else 没有if,并且没有正确缩进。如果您修复它,您可能会得到更好的响应。这听起来像是一个能见度问题。如果将字段标记为 volatile,或者通过同步的 getter 和 setter 访问它会发生什么?
  • 现在会解决这个问题,它显示 else 的原因是我取出了包含 if 语句的数据库查询代码。之后会尝试 volatile/getters。谢谢!
  • 好的,在将实例变量设置为 volatile 并将其包装在 getter/setter 中之后,会发生完全相同的错误,需要两次单击才能返回正确的值并返回 ITSSTILLNULL 的初始字符串值第一次点击
  • 也许我误解了一些东西,但可能是在调用 createdialog2() 方法之后才设置变量,因此在单击它之前不会显示正确的值时间?

标签: java android variables


【解决方案1】:

解决了这个问题,由于某种原因,createdialog2() 方法在方法中的代码运行之前被调用。我只是将 createddialog2 方法调用移动到最后一条日志语句的正下方,它就像一个魅力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2017-04-05
    • 2011-12-08
    • 2012-04-29
    相关资源
    最近更新 更多