-3

I have some TextView which set the text from value saved in SharedPreferences. The values are split as array using "@".

SharedPreferences mark = getSharedPreferences(PREFS_NAME, 0);
        String savestock =  mark.getString("stock", null);
        if (savestock != null) {
            stock = savestock.split("@", -1);
            tvstrength.setText(stock[0]);
            tvavailable.setText(stock[1]);
            tvbrand.setText(stock[2]);
            tvbatch.setText(stock[3]);
            tvexp.setText(stock[4]);
            tvstrength2.setText(stock[5]);
            tvavailable2.setText(stock[6]);
            tvbrand2.setText(stock[7]);
            tvbatch2.setText(stock[8]);
            tvexp2.setText(stock[9]);
            }

This is how the SharedPreferences is saved:

SharedPreferences mark = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = mark.edit();
editor.putString("stock", inStrength + "@" + inamt + "@" + inBrand + "@" + inBatch + "@" + inExp + 
inStrength2 + "@" + inamt2 + "@" + inBrand2 + "@" + inBatch2 + "@" + inExp2);
editor.commit();

However, I got the error java.lang.ArrayIndexOutOfBoundsException: length=9; index=9. The error is caused by tvexp2.setText(stock[9]);

What mistake I made?

user2872856
  • 1,845
  • 2
  • 17
  • 44

2 Answers2

3

Although, 9 string can be seen but according to your split expression you have 8 strings in your array. May be you have forgot to add @ sysmbol after string inExp ** As it can seen **inExp + inStrength2 + there is not @ symbol. Hope that helps you

Abdul Waheed
  • 3,994
  • 4
  • 30
  • 49
2

You forgot to add one "@" symbol after inExp and before inStrength2. Here, I've fixed it for you:

SharedPreferences mark = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = mark.edit();
editor.putString("stock", inStrength + "@" + inamt + "@" + inBrand + "@" + inBatch + "@" + inExp + "@" + inStrength2 + "@" + inamt2 + "@" + inBrand2 + "@" + inBatch2 + "@" + inExp2);
editor.commit();
Sergei Emelianov
  • 4,666
  • 6
  • 23
  • 43