为什么在android中如果/ Else语句总是正在激活

时间:2017-07-21 20:03:50

标签: java android if-statement

我想在timestamp变量中保存时间戳,但总是处于活动状态且timestamp变量的值会发生变化。

    String timestamp = "";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail_product);

    if (!timestamp.equals("")) {

        preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        timestamp= preferences.getString("timestamp", "");
        Toast.makeText(getApplicationContext(), timestamp + "iffff", Toast.LENGTH_LONG).show();

    } else {
        Long tsLong = System.currentTimeMillis() / 1000;
        String ts = tsLong.toString();

        preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("timestamp", ts);
        editor.commit();
        timestamp = preferences.getString("timestamp", "");

        Toast.makeText(getApplicationContext(), timestamp + "elseee", Toast.LENGTH_LONG).show();

    }

}

2 个答案:

答案 0 :(得分:2)

因为在类中声明了timestamp,在调用onCreate之前会被android破坏并重新创建。因此,当您到达onCreate时,timestamp始终为空。您应该将代码放在timestamp之外检索if,然后执行以下测试:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail_product);

    preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    timestamp= preferences.getString("timestamp", "");

    if (!timestamp.equals("")) {
        Toast.makeText(getApplicationContext(), timestamp + "iffff", Toast.LENGTH_LONG).show();
    } else {
        Long tsLong = System.currentTimeMillis() / 1000;
        String ts = tsLong.toString();
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("timestamp", ts);
        editor.commit();
        timestamp = preferences.getString("timestamp", "");

        Toast.makeText(getApplicationContext(), timestamp + "elseee", Toast.LENGTH_LONG).show();

    }
}

答案 1 :(得分:1)

!important此语句将时间戳初始化为""所以时间戳总是==""因此,其他部分将被执行。记住这个函数在这个类中执行一次。所以它总是在iniallization之后执行