Android Development Sharedpreferences Not read the latest data.

Source: Internet
Author: User

Recently, the company's app to achieve access to the app when users manually select the area, and then log in, this time is actually the corresponding server address selected, however, in the implementation process, I found sharedpreferences in the home page always read the latest server address, However, the server address of the login page is the latest change, for example, I just started to enter the research and development server, then switch to the test server, and then the data is read from the research and development server, and then print found home server address is always not read the current latest address, finally looked at the next App's two service did not run in the same process, read the data, finally switched the read mode to multiple process mode, and then read it,

Shared=getcontext (). Getsharedpreferences ("config", mode_multi_process);

However, this is read to the latest server address, later found that when switching to the desktop, the app hanging in the background, in the back to the foreground, app's server address changed back to the previous address, I think this should be saved in the state of the time to save to another variable, Cut back to the time to read the saved variables to achieve the unity of the server address, and then simply changed a way to save the server address, using properties key value pairs to save the server address, so no problem

Package com.shangyi.utils;
Import Android.annotation.SuppressLint;
Import Android.content.Context;
Import android.os.Environment;
Import Android.os.StatFs;
Import Android.text.TextUtils;

Import Android.util.Log;

Import Com.shangyi.log.SyLog;
Import Java.io.BufferedInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import java.util.ArrayList;
Import java.util.Enumeration;
Import java.util.List;
Import Java.util.Map;

Import java.util.Properties; /** * File Operation Tool Class * * @version 1.0 * * * public class FileUtils {private static final String TAG = FileUtils.class.getSi

    Mplename (); /** * Write Properties Information * * @param context Object * @param filename filename with no suffix * @param pkey to save data
    The key * @param pvalue Data * @throws ioexception/public static void WriteProperties (context, String fi Lename, String Pkey, String pvalue) throws IOException {//this.getfilesdir (); This is the path to the files directory under the current app directory//t His.getcachedir ();

        This is to get the cache directory path under the current app directory String FilePath = Context.getfilesdir () + "/" + FileName + ". Properties";
        File File = new file (FilePath);
        if (!file.exists ()) {//check whether the directory file exists or not, create file.createnewfile ();
        Properties pps = new properties ();
        InputStream in = new FileInputStream (FilePath); Pps.load (in);//Read the list of attributes (key and element pairs) from the input stream outputstream out = new FileOutputStream (filePath);//Call Hashtable method Put. Use the GetProperty method to provide parallelism. Force the requirement to use a string for the key and value of the property.
        The return value is the result of the Hashtable call put.
        Pps.setproperty (Pkey, pvalue);  In a format that is suitable for loading into the properties table using the Load method,//Writes the list of properties in this properties table (key and element pairs) to the output stream Pps.store (out, "Update" + Pkey +
    "Name"); }/** * Based onKey Read Value * * @param context * @param filename filename, does not contain suffix * @param key * @return/Publ IC static string Getvaluebykey (context context, string fileName, String key) {String FilePath = Context.getfilesd
        IR () + "/" + FileName + ". Properties";
        Properties pps = new properties ();
            try {inputstream in = new Bufferedinputstream (new FileInputStream (FilePath));
            Pps.load (in);
            String value = Pps.getproperty (key);
            System.out.println ("---------------------------------------------------------------------");
            SYSTEM.OUT.PRINTLN (key + "=" + value);
            System.out.println ("---------------------------------------------------------------------");
        return value;
            catch (IOException e) {e.printstacktrace ();
        return null; }/** * Read all information about Properties * @param context * @param fileName * @throws IOException */public static void Getallproperties (context, String FileName) throws IOException {S
        Tring FilePath = Context.getfilesdir () + "/" + FileName + ". Properties";
        Properties pps = new properties ();
        InputStream in = new Bufferedinputstream (new FileInputStream (FilePath));
        Pps.load (in); Enumeration en = Pps.propertynames ();
            Gets the name of the configuration file while (En.hasmoreelements ()) {String strkey = (String) en.nextelement ();
            String strvalue = Pps.getproperty (strkey);
        System.out.println (strkey + "=" + strvalue);
        }/** * Delete files in this directory * * @param path/public static void Delfile (String path) { if (!
            Textutils.isempty (path)) {File File = new file (path);
            if (file.exists ()) {file.delete (); }}/** * clears all data by filename * @param context * @param filename * @throws IOException
     */public static void Clearallproperties (context context,string fileName) throws ioexception{String fil
        Epath = Context.getfilesdir () + "/" + FileName + ". Properties";
       Boolean D=deletefilewithpath (FilePath);
        /* if (d) {toastutil.defaulttoast (Context.getapplicationcontext (), "Delete succeeded");
        }else {toastutil.defaulttoast (Context.getapplicationcontext (), "Delete failed");
        }*//* Properties PPS = new properties ();
        InputStream in = new Bufferedinputstream (new FileInputStream (FilePath));
        Pps.load (in);  Pps.clear ()//Clear All data/}/** * Write text files in the Android system, the files are stored in the/data/data/package_name/files directory * * @param Context * @param fileName * @param content/public static void write (context context, String Filenam
        E, String content) {if (content = = null) content = ""; try {//mode_private default mode, the file can only be accessed by the application that invokes the method//mode_append asIf the file already exists, it continues to write data to the end of the file, rather than overwriting the original data.
            Mode_world_readable grants all applications the right to read the file.
            Mode_world_writeable gives all applications permission to write to the file.
            FileOutputStream fos = context.openfileoutput (FileName, context.mode_append);
            OutputStreamWriter OSW = new OutputStreamWriter (FOS, "utf-8");
            Osw.write (content);
            Fos.flush ();
            Osw.flush ();
            Osw.close ();
            Fos.close ();
SYLOG.D (TAG, "write success");
        Toastutil.defaulttoast (Context, "write success");
            catch (Exception e) {e.printstacktrace ();
        Toastutil.defaulttoast (Context.getapplicationcontext (), "Write Failed"); }/** * @param context * @param fileName * @param id/public static void Writeid (Cont
        Ext context, string fileName, string id) {if (id = = null) id = "-1";
            try {LOG.D ("id", id);
Mode_private default mode, files can only be accessed by the application that invokes the method            Mode_append writes data to the end of the file if it already exists, rather than overwriting the original data.
            Mode_world_readable grants all applications the right to read the file.
            Mode_world_writeable gives all applications permission to write to the file.
            FileOutputStream fos = context.openfileoutput (FileName, context.mode_private);
            OutputStreamWriter OSW = new OutputStreamWriter (FOS, "utf-8");
            Osw.write (ID);
            Fos.flush ();
            Osw.flush ();
            Osw.close ();
            Fos.close ();
SYLOG.D (TAG, "write success");
            Toastutil.defaulttoast (Context, "write success");
        LOG.D ("Read ID", read (Context,filename));
            catch (Exception e) {e.printstacktrace ();
        Toastutil.defaulttoast (Context.getapplicationcontext (), "Write Failed"); /** * Read Text file * * @param context * @param fileName * @return/public stat IC String Read (context context, String FileName) {try {fileinputstream in = conText.openfileinput (FileName);
                InputStreamReader ISR = new InputStreamReader (in);
                char[] data = new char[in.available ()];
                Isr.read (data);
                string s = new string (data);
                Isr.close ();
                In.close ();
SYLOG.D (TAG, "read Success");
                Toastutil.defaulttoast (context,s);
            return s; catch (Exception e) {e.printstacktrace ();//Toastutil.defaulttoast (Context.getapplicati
            Oncontext (), "failed to read user ID, please login again");
    Return "-1"; /** * Read Input stream * * @param instream * @return/public static String Readinstream (inputs
            Tream instream) {try {bytearrayoutputstream outstream = new Bytearrayoutputstream ();
            byte[] buffer = new BYTE[512];
            int length =-1; while (length = instream.read (buffer))!=-1) {Outstream.write (bUffer, 0, length);
            } outstream.close ();
            Instream.close ();
        return outstream.tostring ();
        catch (IOException e) {log.i ("Filetest", E.getmessage ());
    return null;
        public static file CreateFile (string folderpath, String fileName) {file Destdir = new File (FolderPath);
        if (!destdir.exists ()) {destdir.mkdirs ();
    return new File (folderpath, filename + filename);
    /** * Write pictures to mobile phone * * @param buffer * @param folder * @param fileName * @return * *
        public static Boolean WriteFile (byte[] buffer, string folder, String fileName) {

        Boolean writesucc = false; 

        Boolean sdcardexist = Environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED);
        String FolderPath = ""; if (sdcardexist) {FolderPath = ENvironment.getexternalstoragedirectory () + file.separator + folder + file.separator;
        else {writesucc = false;
        } File Filedir = new file (FolderPath);
        if (!filedir.exists ()) {filedir.mkdirs ();
        File File = new file (FolderPath + fileName);
        FileOutputStream out = null;
            try {out = new FileOutputStream (file);
            Out.write (buffer);
        WRITESUCC = true;
        catch (Exception e) {e.printstacktrace ();
            Finally {try {out.close ();
            catch (IOException e) {e.printstacktrace ();
    } return WRITESUCC; /** * Obtain filename based on file absolute path * * @param filePath * @return/public static String GetFileName (
        String FilePath) {if (Stringutils.isempty (FilePath)) return ""; Return Filepath.substring (filEpath.lastindexof (File.separator) + 1); /** * Gets the filename based on the absolute path of the file but does not contain the extension * * @param filePath * @return/public static String GETF
        Ilenamenoformat (String filePath) {if (Stringutils.isempty (FilePath)) {return "";
        int point = Filepath.lastindexof ('. ');
    Return filepath.substring (Filepath.lastindexof (file.separator) + 1, point); /** * Get file name extension * * @param filename * @return/public static String Getfileformat (stri

        Ng FileName) {if (Stringutils.isempty (fileName)) return "";
        int point = Filename.lastindexof ('. ');
    Return filename.substring (point + 1); /** * Get File Size * * @param filePath * @return/public static long GetFileSize (String fi

        Lepath) {Long size = 0;
        File File = new file (FilePath); if (file!= null && file.exists ()) {size = fIle.length ();
    return size; /** * Get File Size * * @param size BYTE * @return/public static String GetFileSize (Long siz
        e) {if (size <= 0) return "0";
        Java.text.DecimalFormat df = new Java.text.DecimalFormat ("##.##");
        float temp = (float) size/1024;
        if (temp >= 1024) {return Df.format (temp/1024) + "M";
        else {return Df.format (temp) + "K"; /** * Convert File Size * * @param files * @return B/KB/MB/GB/public static String forma
        Tfilesize (Long FileS) {Java.text.DecimalFormat df = new Java.text.DecimalFormat ("#.00");
        String filesizestring = "";
        if (Files < 1024) {filesizestring = Df.format (double) FileS + "B";
        else if (FileS < 1048576) {filesizestring = Df.format (double) files/1024) + "KB";
      else if (FileS < 1073741824) {      filesizestring = Df.format ((double) files/1048576) + "MB";
        else {filesizestring = Df.format (double) files/1073741824) + "G";
    return filesizestring;
        /** * Get directory file Size * * @param dir * @return/public static long Getdirsize (file dir) {
        if (dir = = null) {return 0;
        } if (!dir.isdirectory ()) {return 0;
        Long dirsize = 0;
        file[] files = dir.listfiles ();
            for (File file:files) {if (File.isfile ()) {dirsize + = File.length ();
                else if (file.isdirectory ()) {dirsize + = File.length (); Dirsize + = getdirsize (file);
    Recursive call continuation statistics} return dirsize;
        /** * Get directory file Number * * @param dir * @return/public long getfilelist (file dir) {
        Long Count = 0;
file[] files = dir.listfiles ();        Count = Files.length;
                for (file file:files) {if (File.isdirectory ()) {count = count + getfilelist (file);//recursive
            count--;
    } return count; public static byte[] Tobytes (InputStream in) throws IOException {Bytearrayoutputstream out = new ByteArray
        OutputStream ();
        int ch;
        while (ch = in.read ())!=-1) {out.write (CH);
        } byte buffer[] = Out.tobytearray ();
        Out.close ();
    return buffer; /** * Check if file exists * * @param name * @return/public static Boolean checkfileexists (Stri
        Ng name) {Boolean status;
            if (!name.equals ("")) {File path = Environment.getexternalstoragedirectory ();
            File NewPath = new file (path.tostring () + name);
        Status = Newpath.exists ();
        else {status = FALSE;
    } return status;

   } /** * Check if path exists * * @param path * @return/public static Boolean checkfilepathexists (String
    Path) {return new File (path). exists ();
        /** * Calculates the remaining space of the SD card * * @return return-1, the SD card is not installed/public static long Getfreediskspace () {
        String status = Environment.getexternalstoragestate ();
        Long freeSpace = 0; if (Status.equals (environment.media_mounted)) {try {File path = Environment.getexternalstora
                Gedirectory ();
                Statfs stat = new Statfs (Path.getpath ());
                Long blockSize = Stat.getblocksize ();
                Long availableblocks = Stat.getavailableblocks ();
            FreeSpace = Availableblocks * blocksize/1024;
            catch (Exception e) {e.printstacktrace ();
        } else {return-1;
    return (FreeSpace);
  /** * NEW directory * * @param directoryname   * @return */public static Boolean createdirectory (String directoryname) {Boolean status; if (null!= directoryname &&!directoryname.equals ("")) {File Path = Environment.getexternalstoragedi
            Rectory ();
            File NewPath = new file (path.tostring () + directoryname);
            Status = Newpath.mkdir ();
        Status = TRUE;
        else status = FALSE;
    return status; /** * Check if SD card is installed * * @return/public static Boolean checksavelocationexists () {St
        Ring Sdcardstatus = Environment.getexternalstoragestate ();
         Boolean status;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.