我正在尝试使用我的4个String数组并将它们转换为由“,”分隔的单个字符串。我调试时似乎很容易保存信息;但是,当我尝试使用getString时 - 它不会检索数据。我想确定原因:
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
//Load Data
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(",");
//End Load
Bundle extras = getIntent().getExtras();
int flipper = 0;
for(int i=0;i<debtName.length;i++)
{
if(debtName[i].equals(null) && !extras.equals(null) && flipper!=1)
{
debtName[i] = extras.getString("newDebtName");
debtAmount[i] = extras.getString("newDebtAmount");
debtRate[i] = extras.getString("newDebtRate");
debtPayment[i] = extras.getString("newDebtPayment");
flipper = 1;
}
}
..............
StringBuilder value = new StringBuilder("");
SharedPreferences.Editor editor= sharedPref.edit();
for (String i : debtName) {
value.append(i + ",");
}
editor.putString("debtNames", value.toString());
for (String i : debtAmount) {
value.append(i + ",");
}
editor.putString("debtAmounts", value.toString());
for (String i : debtRate) {
value.append(i + ",");
}
editor.putString("debtRates", value.toString());
for (String i : debtPayment) {
value.append(i + ",");
}
editor.putString("debtPayments", value.toString());
editor.commit();
更正,当在调试之外运行时,这会在:
上给出一个nullpointer异常 SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(","); <---this line
以下是调用活动的位置:
EditText editDebtName = (EditText) findViewById(R.id.dispDebtName);
debtName = editDebtName.getText().toString();
EditText editDebtAmount = (EditText) findViewById(R.id.dispDebtAmount);
String debtAmountStr = editDebtAmount.getText().toString();
EditText editDebtRate = (EditText) findViewById(R.id.dispDebtRate);
String debtRateStr = editDebtRate.getText().toString();
EditText editDebtPayment = (EditText) findViewById(R.id.dispDebtPayment);
String debtPaymentStr = editDebtPayment.getText().toString();
Intent i = new Intent(this, DebtList.class);
i.putExtra("newDebtName", debtName);
i.putExtra("newDebtAmount", debtAmountStr);
i.putExtra("newDebtRate", debtRateStr);
i.putExtra("newDebtPayment", debtPaymentStr);
startActivity(i);
答案 0 :(得分:0)
问题在于这一行:
debtName = sharedPref.getString("debtNames", null).split(",");
密钥debtNames
可能不存在。因此返回null。
当您第一次运行应用并且尚未将任何内容保存到共享首选项时,会发生这种情况。
添加一个null检查并处理这种情况。类似于,如果返回null,则显示默认值,否则显示从共享首选项中读取的值。
答案 1 :(得分:0)
我已经放弃了显而易见的事实,即没有有效的方法可以做到这一点,所以我现在已经将40个变量硬编码到应用程序中。如果有人想出任何有用的东西,请随时发布,我会经常检查这个。