1

In an app I am using SharedPrefernces to save/load (serialize/deserialize) some objects.

This is the deserialization code:

private void loadData() {

    String str = sharedPreferences.getString(PREF_TAG, null);

    byte[] bytes = Base64.decode(str, Base64.DEFAULT);

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream input = new ObjectInputStream(bais);
        arrayOfObjects = (ArrayList<MyObject>) input.readObject();
    } catch (Exception e) {
        Log.i("BUG", "error decoding serialized objects: " + e.toString());
    }

    if (arrayOfObjects == null) {
        Log.i("BUG", "serious problem!");
    }

}

But whenever I compile this project, the line:

arrayOfObjects = (ArrayList<MyObject>) input.readObject();

causes a warning that the class containing this method "uses unchecked or unsafe operations."

How can I get rid of this warning or change my code to be more safe?

Guillaume S
  • 1,266
  • 2
  • 17
  • 28
Nerdy Bunz
  • 3,581
  • 2
  • 28
  • 60
  • Did you check this https://stackoverflow.com/questions/197986/what-causes-javac-to-issue-the-uses-unchecked-or-unsafe-operations-warning and this https://stackoverflow.com/questions/23749786/uses-unchecked-or-unsafe-operations – AskNilesh Sep 04 '18 at 10:01

3 Answers3

7

In this case that warinig is shown because you are parsing directly the result of

input.readObject();

That returns an Object of type Object, (that is so generic), into an ArrayList, and the compiler tries to say you that, it could be any other type of objects.

In my opinion its not an important warning if that instruction in your code is always returning ArrayList, so i would add to your method definition.

@SuppressWarnings("unchecked")
Oldskultxo
  • 845
  • 6
  • 16
4

I had the same problem and solved it by adding :

@SuppressWarnings("unchecked")
public class className extends AppCompatActivity {
...
}

I hope this will help

Jhakiz
  • 1,092
  • 4
  • 13
0

I solved this problem with add :

@SuppressWarnings("unchecked")
public class CommLockInfoManager {
sana ebadi
  • 4,318
  • 29
  • 36