开发者

Object de-serialization Problem in android application

I have a class name ObjectSerializer. That is :

public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
    if (obj == null)
        return "";
    ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
    ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
    objStream.writeObject(obj);
    objStream.close();
    return encodeBytes(serialObj.toByteArray());
}

public static Object deserialize(String str) throws IOException,
        ClassNotFoundException {
    if (str == null || str.length() == 0)
        return null;
    ByteArrayInputStream serialObj = new ByteArrayInputStream(
            decodeBytes(str));
    ObjectInputStream objStream = new ObjectInputStream(serialObj);
    return objStream.readObject();
}

public static String encodeBytes(byte[] bytes) {
    StringBuffer strBuf = new StringBuffer();

    for (int i = 0; i < bytes.length; i++) {
        strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
        strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
    }

    return strBuf.toString();
}

public static byte[] decodeBytes(String str) {
    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length(); i += 2) {
        char c = str.charAt(i);
        bytes[i / 2] = (byte) ((c - 'a') << 4);
        c = str.charAt(i + 1);
        bytes[i / 2] += (c - 'a');
    }
    return bytes;
}
}

now I have test it using Console application Like:

    public static void main(String[] args) throws IOException,
        ClassNotFoundException {
    HighScore highScore = new HighScore();
    highScore.setScore(10);
    highScore.setUsername("rokon");

    ArrayList<HighScore> list = new ArrayList<HighScore>();
    list.add(highScore);
    String seralized = null;
    try {
        seralized = ObjectSerializer.serialize(list);

        System.out.println(seralized);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Object obj = ObjectSerializer.deserialize(seralized);
    ArrayList<HighScore> l = (ArrayList<HighScore>) obj;

    HighScore h= l.get(0);
    System.out.println(h.getUsername() + "\t" + h.getScore());
}

but same things is not working in my android application. Can anyone tell me what is the problem in android app.

and code I used int android class

    public class HighScorePreferenceUtil {
public static String APP_SHARED_PREF = "com.wneeds.quiz";
private SharedPreferences preferences;
private final String key = "HighScore";
private Editor editor;
private ArrayList<HighScore> highScores;
private Context context;

public HighScorePreferenceUtil(Context context) {
    this.preferences = context.getSharedPreferen开发者_Python百科ces(APP_SHARED_PREF,
            Activity.MODE_PRIVATE);
    this.context = context;
}

public void addScore(HighScore score) {
    if (score != null) {
        try {
            this.editor = preferences.edit();
            editor.putString(key, ObjectSerializer.serialize(score));
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    editor.commit();
}

public ArrayList<HighScore> getScores() {
    if (highScores == null) {
        highScores = new ArrayList<HighScore>();
    }
    try {
        String scores = preferences.getString(key, "empty");
        Object obj = ObjectSerializer.deserialize(scores);

        if (!scores.equals("empty")) {
            ArrayList<HighScore> list = (ArrayList<HighScore>) obj;
            highScores = list;
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return highScores;
}
}

Im getting ClassCastException. Herte is the logCat reports.

09-13 22:29:27.083: ERROR/AndroidRuntime(983): FATAL EXCEPTION: main
09-13 22:29:27.083: ERROR/AndroidRuntime(983): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rokon/com.rokon.SharedPreferenceDemoActivity}: java.lang.ClassCastException: com.rokon.HighScore
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.os.Looper.loop(Looper.java:123)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at java.lang.reflect.Method.invokeNative(Native Method)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at java.lang.reflect.Method.invoke(Method.java:521)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at dalvik.system.NativeStart.main(Native Method)
09-13 22:29:27.083: ERROR/AndroidRuntime(983): Caused by: java.lang.ClassCastException: com.rokon.HighScore
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at com.rokon.HighScorePreferenceUtil.getScores(HighScorePreferenceUtil.java:51)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at com.rokon.SharedPreferenceDemoActivity.onCreate(SharedPreferenceDemoActivity.java:54)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627
09-13 22:29:27.083: ERROR/AndroidRuntime(983):     ... 11 more


I am not sure if this is the reason but:

You should check with the debugger that you have a working instance of HighScore that you pass to the serialize method. If you pass null, you return an empty string that you than add to the SharedPreferences in the addScore() method. If that happens, you will get the empty string back when you deserialize it. And the empty string will create the ClassCastException.

So my advise: Do more null checks and/or stop returning the empty string when you try to serialize a null reference and return your "empty" string instead so that the !scores.equals("empty") will work in this case, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜