简体   繁体   中英

Is SharedPreference a good way to store large chunks of data?

I'm currently storing large chunks of user data as JSON string in SharedPreferences. It's working nicely but I wonder if it will cause any problems, for example large app size or memory problems.

Are there any better or recommended way to store large chunks of data in Android app, other than SharedPreferences?

Why don't you just store it in SQLite DB? You can organise the data in a well format.

I think it's not good practice to save large data in SharedPreference . You can store large data in either database or create a read or writable file.

You can create readable & writable file like

Write file by this method

public static void writeToFile(String data,Context context, String fileName) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(fileName+".txt", Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }

Read file by this method

    public static String readFromFile(Context context, String fileName) {

        String ret = "";

        try {
            InputStream inputStream = context.openFileInput(fileName + ".txt");

            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader       = new BufferedReader(inputStreamReader);
                String receiveString                = "";
                StringBuilder stringBuilder         = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }

        return ret;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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