2017-07-21 46 views
-1

我想要保存timestamp變量中的時間戳,但總是處於活動狀態,並且timestamp變量的值發生變化。爲什麼在Android如果/否則總是其他語句激活

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

因爲timestamp是在類中聲明的,所以在調用onCreate之前,它被android破壞並重新創建。所以當你到達onCreatetimestamp總是空的。你應該把代碼檢索iftimestamp,然後做你的測試是這樣的:

@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(); 

    } 
} 
+0

非常感謝。 – Saeidhp

1

String timestamp = "";這條語句初始化時間戳「」時間戳所以總是==「」因此,其他部分將會被執行。記住這個函數在這個類中執行一次。所以它總是在執行完之後執行

+0

在else語句我定義時間戳,所以只在第一應該去別的部分。怎樣才能定義真正的時間戳。 – Saeidhp

+0

是的,我明白了。但是,創建該活動時,onCreate只會執行一次 – henrybbosa