I am trying to save byte array data in arraylist which worked fine as,
SharedPreferences sPrefs=PreferenceManager.getDefaultSharedPreferences(FirstActivity.this); SharedPreferences.Editor sEdit=sPrefs.edit(); for(int i=0;i<byteArrayList.size();i++) { sEdit.putString("val"+i,byteArrayList.get(i).toString()); } sEdit.putInt("size",byteArrayList.size()); sEdit.commit();I am retrieving byte array data by using,
SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(ViewImagesActivity.this); myAList=new ArrayList<byte[]>(); int size=sPrefs.getInt("size",0); for(int j=0;j<size;j++) { myAList.add(sPrefs.getString("val"+j,"")); // giving error for type mismatch for byte[] and string }- please help me to sort out this issue..
- please tell me if any other way to store and retrieve for this.
- Thank you in advance
Add a comment
|
3 Answers
try below code:-
myAList.add(sPrefs.getString("val"+j,null).getBytes(Charset.forName("UTF-8")));
Error shown because array list type of byte array
myAList=new ArrayList<byte[]>();
and you add value of string so gives your error .
3 Comments
user3707205
giving this error : The method add(byte[]) in the type ArrayList<byte[]> is not applicable for the arguments (String)
duggu
@user3707205 change string to byte array
user3707205
I got solution bro.. Thanks for your kind help also... thank you
You are trying to store String in a Byte type list:
myAList.add(sPrefs.getString("val"+j,));
You can use int in place of Byte. There is a standard method putInt and getInt for storing and retrieving data in SharedPreferences
1 Comment
Green goblin
Is it necessary to use Byte array? Can you use int array instead?
You have to call the add method with a byte[] parameter. The reverse operation is performed with String.getBytes method, so change the relevant line of your code:
myAList.add(sPrefs.getString("val"+j,"").getBytes());
2 Comments
jww
The answer was flagged as low quality. Perhaps you could explain how/why the code works to ensure its not deleted.
Juan Sánchez
Oh, low quality? The one who asks the question gave me the thanks as it works, and just for not being verbose in my answer you say it is low quality? :D