简体   繁体   English

Android 使用 SharedPreferences 时应用程序崩溃

[英]Android App crashes when using SharedPreferences

I made this app to get a list of friends and store it in sharedPreferences.我制作了这个应用程序来获取朋友列表并将其存储在 sharedPreferences 中。 When I run the application it doesn't show any error and crashes.当我运行应用程序时,它不会显示任何错误并崩溃。

here's my code这是我的代码

package com.abhishek.sharedpreferances;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    EditText editTextFriends = (EditText) findViewById(R.id.editTextFriends);
    Button buttonSave = (Button) findViewById(R.id.buttonSave);
    TextView textViewFriends = (TextView) findViewById(R.id.textViewFriends);

    SharedPreferences sharedPreferences = this.getSharedPreferences("com.abhishek.sharedpreferances", Context.MODE_PRIVATE);

    ArrayList<String> friends = new ArrayList<>();
    ArrayList<String> newFriends = new ArrayList<>();


    public void save(View view) throws IOException {
        friends.add(editTextFriends.getText().toString());

        //ObjectSerializer.serialize(friends);
        try {
            sharedPreferences.edit().putString("friends",ObjectSerializer.serialize(friends)).apply();
        } catch (Exception e) {
            e.printStackTrace();
        }

        newFriends = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("friends",ObjectSerializer.serialize(new ArrayList<String>())));

        assert newFriends != null;
        textViewFriends.setText(newFriends.toString());


    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

And I created ObjectSerializer java class to store Array list into the sharedPreferences into the application I have provided the class below please check it out我创建了 ObjectSerializer java class 以将数组列表存储到 sharedPreferences 到应用程序中我提供了下面的 class 请检查一下

And this is my ObjectSerializer java class这是我的 ObjectSerializer java class

package com.abhishek.sharedpreferances;

import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerializer {


    public static String serialize(Serializable obj) throws IOException {
        if (obj == null) return "";
        try {
            ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
            objStream.writeObject(obj);
            objStream.close();
            return encodeBytes(serialObj.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object deserialize(String str) throws IOException {
        if (str == null || str.length() == 0) return null;
        try {
            ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
            ObjectInputStream objStream = new ObjectInputStream(serialObj);
            return objStream.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    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;
    }

}

Do try keeping sharedPreferences.edit() after putString and getString could get the string saved from SharedPreferences.在 putString 和 getString 可以从 SharedPreferences 中获取保存的字符串之后,请尝试保留sharedPreferences.edit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM