2017-07-06 46 views
0

在下面寫的代碼中,無論我的購物車活動何時啓動,以及編譯器是否在線:HashMap<String, String> cart = session2.getUserDetails();那麼它默認加載默認項目值而不是加載空值加載的值是上一次運行。任何人都可以請求我建議我在我的代碼中錯了嗎?Android SharedPreference值自動加載

public class Cart extends AppCompatActivity { 

ListView lvCartItems; 
Button bClear; 
Button bShop; 
TextView tvTotalPrice; 

// Session Manager Class 
ProductSessionManager session2; 

ArrayList<CartItem> cartItems = new ArrayList<CartItem>(); 
Context context = Cart.this; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_cart); 

    textHome = (TextView) findViewById(R.id.text_home); 
    textSchedules = (TextView) findViewById(R.id.text_account); 
    textMusic = (TextView) findViewById(R.id.text_cart); 
    tvTotalPrice=(TextView)findViewById(R.id.tvTotalPrice); 

    lvCartItems = (ListView) findViewById(R.id.lvCartItems); 
    LayoutInflater layoutInflater = getLayoutInflater(); 


    // Session class instance 
    session2 = new ProductSessionManager(this); 


    // get user data from session 
    HashMap<String, String> cart = session2.getUserDetails(); 

    // item 
    String item1 = cart.get(ProductSessionManager.KEY_item1); 
    //quantity 
    String quantity1 = cart.get(ProductSessionManager.KEY_quantity1); 
    //rate 
    String rate1 = cart.get(ProductSessionManager.KEY_rate1); 
+0

請在不再需要時清除您的共享偏好值! –

+0

'使用HashMap cart = null;'而不是'HashMap cart = session2.getUserDetails();'! – tahsinRupam

+0

這就是使用Sharedpreferences維護會話的重點。它會保留以前的值,直到您更新它們或清除它們。如果您不希望以前的值清除您的共享首選項。 – sumit

回答

0

使用此選項可清除會話。

SharedPreferences pref = 
context.getSharedPreferences("shared_preferences_name", "mode"); 
SharedPreferences.Editor editor = pref.edit(); 
editor.clear(); 
editor.commit();