简体   繁体   中英

SharedPreferences getString returns null

I keep getting null instead of the expected string. I have passed getSharedPreferences the context of the app and the proper key. I'll upload the XML file. I'm not sure what's going on here though.

java.lang.NullPointerException: println needs a message on line Log.d("MomentPrefTimeStamp", momentData.getString("caption", null)); Nothing in the preference file shows up, however the keys are correct and the momentData is a valid SharedPreferences object. At least according to the debugger.

This is the XML, below is the code.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="time_stamp">1529509324</string>
<string name="img_uri">content://com.example.android.fileprovider/my_images/JPEG_20180620_114201_1480896410651074556.jpg</string>
<string name="caption">Captionas</string>
</map>

Why am I not able to get my data with the correct key and context?

-

    if (prefsDir.exists() && prefsDir.isDirectory()) {
        String[] list = prefsDir.list();
        Log.d("PrefList", list.toString());
        //Iterate through every file in the directory
        for (String title : list) {
            Log.d("prefTitle", title);
            //Only open files with our MOMENT marker, since there will be other shared_pref files inside folder.
            String[] momentID = title.split("_");
            Log.d("StringMoment", momentID.toString());
            Log.d("StringMoment1", momentID[0]);
            if (momentID.length > 1) {
                Log.d("StringMoment2", momentID[1]);
                if (momentID[1].equals("JPEG.xml")) {
                    Log.d("momentTitle", title);
                    SharedPreferences momentData = this.getSharedPreferences(title, this.MODE_PRIVATE);
                    Log.d("MomentPref", momentData.toString());
                    Log.d("MomentPrefTimeStamp", momentData.getString("caption", null));
                    moments.add(momentData);
                }
            }
        }
    }

    return moments;

If you are getting you're SharedPreferences through string tricks and file directories, be sure to trim the extension name off of the file name. I don't know why it was still giving me a SharedPreference Object instead of a null pointer exception, but that is the problem.

1234242_JPEG.xml needs to be 1234242_JPEG to get a proper SharedPreference file. Below is the fix.

                    String name = title.substring(0, title.lastIndexOf('.'));
                    Log.d("MomentName", name);
                    SharedPreferences momentData = this.getSharedPreferences(name, this.MODE_PRIVATE);

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