【发布时间】:2017-02-13 19:11:16
【问题描述】:
注意:“null”实际上是我设置为默认值的字符串
我保存在 SharedPreference 中的代码
billText = (EditText) findViewById(R.id.billNumber);
tableNumberText = (EditText) findViewById(R.id.tableNumber);
amountText = (EditText) findViewById(R.id.amount);
remarksText = (EditText) findViewById(R.id.remarks);
submit = (Button) findViewById(R.id.submitButton);
SharedPreferences sharedPreferences = getSharedPreferences(SharedPreference.Form.FORM, MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tableNumberText.getText().toString() != null || tableNumberText.getText().toString() != "") {
editor.putString(SharedPreference.Form.TABLE_NUMBER, tableNumberText.getText().toString());
Toast.makeText(FormActivity.this, "ABC", Toast.LENGTH_LONG).show();
}
if (amountText.getText().toString() != null || amountText.getText().toString() != "") {
editor.putString(SharedPreference.Form.AMOUNT, amountText.getText().toString());
}
if (billText.getText().toString() != null || billText.getText().toString() != "") {
editor.putString(SharedPreference.Form.BILL_NUMBER, billText.getText().toString());
}
if (remarksText.getText().toString() != null || remarksText.getText().toString() != "") {
editor.putString(SharedPreference.Form.REMARKS, remarksText.getText().toString());
}
editor.commit();
startActivity(new Intent(getApplicationContext(), FeedbackActivity.class));
}
});
我推送数据的代码
jsonObj.put("bill", sharedPreferences.getString(SharedPreference.Form.BILL_NUMBER, "null"));
jsonObj.put("table", sharedPreferences.getString(SharedPreference.Form.TABLE_NUMBER, "null"));
jsonObj.put("amount", sharedPreferences.getString(SharedPreference.Form.AMOUNT, "null"));
jsonObj.put("remarks", sharedPreferences.getString(SharedPreference.Form.REMARKS, "null"));
editor.clear();
editor.commit();
编辑:
我打算做什么:通过 SharedPreference 保存数据。我首先通过 Activity(第一个代码块)保存数据,然后将数据推送到后端。有四个文本字段 (EditText) 我从中获得 String 数据。
预期行为:当我使用方法时
jsonObj.put("key", SharedPreference.getString(key, default-value)
我应该得到我保存在后端的 Activity 中的值。
结果:
在后端,我得到的不是我输入的内容,而是屏幕截图中显示的内容。
奇怪的部分:尽管如您所见,所有四个字段的代码都相同(有四个EditText 字段供用户输入数据)其中三个获取默认字符串,即"null",其中一个(金额)保持空白。
PS:在我运行的所有这些测试中,我从未将所有字段都留空。
【问题讨论】:
-
第一次调用
if(TextUtils.isEmpty(tableNumberText.getText().toString()))而不是if (tableNumberText.getText().toString() != null || tableNumberText.getText().toString() != "") -
@IntelliJAmiya 不,它没有解决错误。我试过了。
-
什么奇怪??...为您的问题添加更多详细信息...首先,它总是让您根据您当前的代码将空格放在编辑文本上。
-
@SRBbans 如果你看后台数据库的截图,你可以看到,当bug出现时,三个字段获取了默认String中的数据,即
"null",而一个字段始终为空白。 总是,无论我将哪些字段留空,即使所有字段的代码都是相同的。这就是 strange 部分。 -
okey ..... 但是您应该尝试将
edit()和commit()放在 sharedpref 操作之前和之后.. 就像在onClick., 中一样,并注意您为值提供的键......并在将其称为BUG之前对您的代码进行适当的研究。
标签: android json sharedpreferences android-sharedpreferences