如果condition无法识别赋值给变量的值

时间:2015-02-20 13:11:26

标签: java android sharedpreferences

我展示了我的部分代码。我已将描述的值存储在sharedpreferences中。当我使用断点检查if条件时,它具有我希望它具有的值。但是当我完成流程时,代码就会进入其他条件。但我希望它进入if条件bz描述有一个值。那么我怎么能过来呢?

public static String description = "descriptionKey";
public static String price = "priceKey";
public static String quantity = "quantityKey";

SharedPreferences sharedpreferences;

public static final String MyPREFERENCES = "MyPrefs";

public void run(View view) {

    Editor editor = sharedpreferences.edit();

    editor.putString("quantity", quantity);
    editor.putString("price", price);
    editor.putString("description", description);

    editor.commit();

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cart_activity);

    sharedpreferences = getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);

     if (sharedpreferences.contains("description")) {

        description = sharedpreferences.getString("description",
                description);
        quantity = sharedpreferences.getString("quantity", quantity);
        price = sharedpreferences.getString("price", price);
    } else {
        quantity = getIntent().getStringExtra("quantity");
        price = getIntent().getStringExtra("price");
        description = getIntent().getStringExtra("description");
    }

2 个答案:

答案 0 :(得分:1)

那可能应该是 if (sharedpreferences.contains("description")) {

答案 1 :(得分:1)

更改以下行

if (sharedpreferences.contains(description))

if (sharedpreferences.contains("description"))

希望这会对你有所帮助。