私は4つの文字列配列をsharedpreferenceに保存することに取り組んでいます。現在、配列をコンマで区切った文字列に分解しています。文字列に移動すると、必要に応じて正確にピースが保存されます。ただし、データを「ロード」して配列に戻すと、空になります (null ではありません)。アレイを元に戻すためにこれを修正する方法を判断できません。以下は私の活動です:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debtlist);
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
int counter = 0;
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
Bundle extras = getIntent().getExtras();
int trigger = 0;
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] == null && extras != null && trigger == 0)
{
debtName[i] = extras.getString("debtName");
debtAmount[i] = extras.getString("debtAmount");
debtRate[i] = extras.getString("debtRate");
debtPayment[i] = extras.getString("debtPayment");
trigger = 1;
counter++ ;
}
}
TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] != null)
{
TableRow tr = new TableRow(this);
TextView tv0 = new TextView(this);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
TextView tv3 = new TextView(this);
TableRow.LayoutParams trlp = new TableRow.LayoutParams();
tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
trlp.span = 3;
tr.setLayoutParams(trlp);
tv0.setText("" + debtName[i]);
tv1.setText("" + debtAmount[i]);
tv2.setText("" + debtPayment[i]);
tv3.setText("" + i);
tr.addView(tv0);
tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);
tl.addView(tr);
}
}
SharedPreferences.Editor editor= sharedPref.edit();
String debtNames = convertArrayToString(debtName, counter);
editor.putString("debtNames", debtNames).commit();
TextView disp = (TextView) findViewById(R.id.dispAdditionalAmount);
disp.setText("" + debtNames); //This is how I confirm that the convertArrayToString is functioning properly
}
public static String convertArrayToString(String[] array, int stop){
String str = "";
for (int i = 0;i<stop; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<stop-1){
str = str+",";
}
}
return str;
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}