0
  • 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

3 Answers 3

1

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 .

Sign up to request clarification or add additional context in comments.

3 Comments

giving this error : The method add(byte[]) in the type ArrayList<byte[]> is not applicable for the arguments (String)
@user3707205 change string to byte array
I got solution bro.. Thanks for your kind help also... thank you
0

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

Is it necessary to use Byte array? Can you use int array instead?
0

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

The answer was flagged as low quality. Perhaps you could explain how/why the code works to ensure its not deleted.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.