【问题标题】:Can not access SharedPreferences value in another class after restart重启后无法访问另一个类中的 SharedPreferences 值
【发布时间】:2014-09-26 11:53:00
【问题描述】:

我正在使用 csipsimple 代码并自定义它以通过从 webservice 获取 json 值来显示品牌名称。我正在使用 SharedPreferences 来存储值。

一旦应用程序被强制关闭,或者设备重启,SharedPreferences 就会丢失。我正在使用 commit 和 clear 但值仍然为 null 。

BasePrefsWizard 是负责提取 Web 数据的类,而 DialerFragment 是我调用 BrandName 的另一个类(它是 SavedBrand/ 代码中的品牌)

package com.mydial.wizards;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.EditTextPreference;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mydial.api.SipManager;
import com.mydial.api.SipProfile;
import com.mydial.db.DBProvider;
import com.mydial.models.Filter;
import com.mydial.ui.SipHome;
import com.mydial.ui.dialpad.DialerFragment;
import com.mydial.ui.filters.AccountFilters;
import com.mydial.ui.prefs.GenericPrefs;
import com.mydial.utils.AccountListUtils;
import com.mydial.utils.Log;
import com.mydial.utils.PreferencesProviderWrapper;
import com.mydial.utils.PreferencesWrapper;
import com.mydial.utils.AccountListUtils.AccountStatusDisplay;
import com.mydial.utils.animation.ActivitySwitcher;
import com.mydial.wizards.WizardUtils.WizardInfo;
import com.mydial.wizards.impl.Advanced;
import com.worldfone.R;



@SuppressLint("NewApi") public class BasePrefsWizard extends GenericPrefs {

    public static final int SAVE_MENU = Menu.FIRST + 1;
    public static final int TRANSFORM_MENU = Menu.FIRST + 2;
    public static final int FILTERS_MENU = Menu.FIRST + 3;
    public static final int DELETE_MENU = Menu.FIRST + 4;

     private PreferencesProviderWrapper prefProviderWrapper;
    private static final String THIS_FILE = "Base Prefs wizard";

    protected SipProfile account = null;
    private Button saveButton,cancel;
    private String wizardId = "";
    private WizardIface wizard = null;
    private BroadcastReceiver mReceiver;
    IntentFilter intentFilter;


    public static final String myData = "mySharedPreferences";


     public static String bal = null;

     public static  String sip = null;

     public static  String header = null;

     public static  String date = null;



     public static String savedBal="";
     public static String savedSip="";
    public static String savedBrand="";


     public static String webArray[] =new String[6];

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {



        // Get back the concerned account and if any set the current (if not a
        // new account is created)

        Intent intent = getIntent();
        long accountId = 1;

        //intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);

        // TODO : ensure this is not null...
    //  setWizardId(intent.getStringExtra(SipProfile.FIELD_WIZARD));
        setWizardId();

        account = SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);

        super.onCreate(savedInstanceState);


         prefProviderWrapper = new PreferencesProviderWrapper(this);




        // Bind buttons to their actions
         cancel = (Button) findViewById(R.id.cancel_bt);
        //cancel.setEnabled(false);
        cancel.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View v)
            {

                isOnline(); 


                //saveAndFinish();



            }
        });

        saveButton = (Button) findViewById(R.id.save_bt);
        //saveButton.setEnabled(false);
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) 
            {
                //setResult(RESULT_CANCELED, getIntent());


                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
                finish();
                System.exit(0);

            }
        });
          wizard.fillLayout(account);

          loadValue(); 

    }


    public void isOnline() 
    {
        ConnectivityManager connMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);

       NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

      if (networkInfo != null && networkInfo.isConnected()) 
        {



        try
        {


        String webAccessNumberLink="http://myweblink.info/test/code.php?user=1234";


        new webAccessNumber().execute(webAccessNumberLink);

        }
        catch(Exception e)
        {
        //  System.out.println("exception in basepreference "+e);
        }

        }

      else 
      {
       // display error
          showNetworkAlert(); 

       }


        }

    void showNetworkAlert() 
    {
        new AlertDialog.Builder(this)
        .setTitle("Alert")
        .setMessage(
                "Please make sure you have Network Enabled")
        .setNeutralButton("OK", new DialogInterface.OnClickListener()
        {

            public void onClick(DialogInterface dialog, int which)
            {
                /*Intent siphome = new Intent(getApplicationContext(),SipHome.class);
                startActivity(siphome);*/

            }
        }).show();
    }


    public void  saveArray(String[] arrayOfweb) 
     {

         int mode = Context.MODE_PRIVATE;
            SharedPreferences mySharedPreferences =this.getSharedPreferences(myData,
                            mode);

            SharedPreferences.Editor editor = mySharedPreferences.edit();

            String f1 = arrayOfweb[0];
            String f2 = arrayOfweb[1];
            String f3 = arrayOfweb[2];
            String f4 = arrayOfweb[3];


            for(int i=0;i<arrayOfweb.length;i++)
            {


            }

            //byMe added below to make preferences persistant
            editor.clear();

            editor.putString("balance",f1);
            editor.putString("sipp",f2);

            editor.putString("brand",f3);

            editor.putString("prfx",f4);

            editor.commit();        

            loadValue(); 
    }



     private void loadValue() 
     {

            int mode = Context.MODE_PRIVATE;
            SharedPreferences mySharedPreferences = this.getSharedPreferences(myData,
                    mode);



             savedBal= mySharedPreferences.getString("balance", "");
             savedSip = mySharedPreferences.getString("sipp", "");

             savedBrand = mySharedPreferences.getString("barnd", "");



        }

    private boolean isResumed = false;
    @Override
    protected void onResume() 
    {
        super.onResume();
        isResumed = true;
        updateDescriptions();
        updateValidation();
        //byMe





    }

    @Override
    protected void onPause()
    {
        super.onPause();
        isResumed = false;
        //this.unregisterReceiver(this.mReceiver);
    }
    private boolean setWizardId() 
    {


        try {
            wizard=Advanced.class.newInstance();
//  wizard = (WizardIface) wizardInfo.classObject.newInstance();
        } catch (IllegalAccessException e) {
            Log.e(THIS_FILE, "Can't access wizard class", e);
            /*if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
                return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
            }*/
            return false;
        } catch (InstantiationException e) {
            Log.e(THIS_FILE, "Can't access wizard class", e);
/*          if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
                return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
            }
*/          return false;
        }
        //wizardId = wId;
        wizard.setParent(this);
        if(getSupportActionBar() != null) {
            getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
        }
        return true;
    }
    private boolean setWizardId(String wId) {
        if (wizardId == null) {
            return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
        }

        WizardInfo wizardInfo = WizardUtils.getWizardClass(wId);
        if (wizardInfo == null) {
            if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
                return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
            }
            return false;
        }

        try {
            wizard = (WizardIface) wizardInfo.classObject.newInstance();
        } catch (IllegalAccessException e) {
            Log.e(THIS_FILE, "Can't access wizard class", e);
            if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
                return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
            }
            return false;
        } catch (InstantiationException e) {
            Log.e(THIS_FILE, "Can't access wizard class", e);
            if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
                return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
            }
            return false;
        }
        wizardId = wId;
        wizard.setParent(this);
        if(getSupportActionBar() != null) {
            getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
        }
        return true;
    }

    @Override
    protected void beforeBuildPrefs() {
        // Use our custom wizard view
        setContentView(R.layout.wizard_prefs_base);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(isResumed) {
            updateDescriptions();
            updateValidation();
        }
    }




    private void resolveStatus()
    {

        AccountStatusDisplay accountStatusDisplay = AccountListUtils
                .getAccountDisplay(this, 1);
        //status.setTextColor(accountStatusDisplay.statusColor);
        //status.setText(accountStatusDisplay.statusLabel);

    }

    /**
     * Update validation state of the current activity.
     * It will check if wizard can be saved and if so 
     * will enable button
     */
    public void updateValidation()
    {
        cancel.setEnabled(wizard.canSave());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    //  menu.findItem(SAVE_MENU).setVisible(wizard.canSave());

        return super.onPrepareOptionsMenu(menu);
    }


    private static final int CHOOSE_WIZARD = 0;
    private static final int MODIFY_FILTERS = CHOOSE_WIZARD + 1;

    private static final int FINAL_ACTIVITY_CODE = MODIFY_FILTERS;

    private int currentActivityCode = FINAL_ACTIVITY_CODE;
    public int getFreeSubActivityCode()
    {
        currentActivityCode ++;
        return currentActivityCode;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {

        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * Save account and end the activity
     */



    public void saveAndFinish() 
    {
        //this.registerReceiver(mReceiver, intentFilter);   


        saveAccount();
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        Intent it = new Intent(this,SipHome.class);
        startActivity(it);
        finish();



    }

    void updateStatus() 
    {
        AccountStatusDisplay accountStatusDisplay = AccountListUtils
                .getAccountDisplay(this, account.id);

    }

    /*
     * Save the account with current wizard id
     */
    private void saveAccount() {
        saveAccount(wizardId);
    }


    @Override
    protected void onDestroy() {
        //byMe


        super.onDestroy();

        getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
        saveArray(webArray);
    }

    /**
     * Save the account with given wizard id
     * @param wizardId the wizard to use for account entry
     */
    private void saveAccount(String wizardId) {
        boolean needRestart = false;

        PreferencesWrapper prefs = new PreferencesWrapper(getApplicationContext());
        account = wizard.buildAccount(account);
        account.wizard = wizardId;
        if (account.id == SipProfile.INVALID_ID) {
            // This account does not exists yet
            prefs.startEditing();
            wizard.setDefaultParams(prefs);
            prefs.endEditing();
            Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());

            // After insert, add filters for this wizard 
            account.id = ContentUris.parseId(uri);
            List<Filter> filters = wizard.getDefaultFilters(account);
            if (filters != null) {
                for (Filter filter : filters) {
                    // Ensure the correct id if not done by the wizard
                    filter.account = (int) account.id;
                    getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());
                }
            }
            // Check if we have to restart
            needRestart = wizard.needRestart();

        } else {
            // TODO : should not be done there but if not we should add an
            // option to re-apply default params
            prefs.startEditing();
            wizard.setDefaultParams(prefs);
            prefs.endEditing();
            getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
        }

        // Mainly if global preferences were changed, we have to restart sip stack 
        if (needRestart) {
            Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
            sendBroadcast(intent);
        }
    }

    @Override
    protected int getXmlPreferences() {
        return wizard.getBasePreferenceResource();
    }

    @Override
    protected void updateDescriptions() {
        wizard.updateDescriptions();
    }

    @Override
    protected String getDefaultFieldSummary(String fieldName) {
        return wizard.getDefaultFieldSummary(fieldName);
    }

    private static final String WIZARD_PREF_NAME = "Wizard";

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return super.getSharedPreferences(WIZARD_PREF_NAME, mode);
    }


     private class webAccessNumber extends AsyncTask<String, Void, String> 
        {
           //String balance;
         ProgressDialog progressDialog; 

            @Override
            protected String doInBackground(String... params) {

                return getAccessNumber(params[0]);
            }

            @Override
            protected void onPostExecute(String result)
            {
                if(result!=null)
                {
                    try {

                        System.out.println("value of webAccessNumber   "+result);



                        byte[] decoded = Base64.decode(result,Base64.DEFAULT);

                        String decodedStr =new String(decoded, "UTF-8");

                        //System.out.println(decodedStr);


                        JSONArray arr = new JSONArray(decodedStr);

                          //loop through each object
                          for (int i=0; i<arr.length(); i++)
                          {

                          JSONObject jsonObject = arr.getJSONObject(i);



                          bal = jsonObject.getString("balance");

                         sip = jsonObject.getString("server");

                         header = jsonObject.getString("brand");






                          webArray[1]=bal;
                          webArray[2]=sip;
                          webArray[3]=barnd;


                          saveArray(webArray);

                          saveAndFinish();

                         progressDialog.dismiss();
                        }


                    }
                    catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                }

            @Override
            protected void onPreExecute()
            {
                 super.onPreExecute();
                progressDialog = new ProgressDialog(BasePrefsWizard.this);
                progressDialog.setMessage("Loading..............");
                progressDialog.setIndeterminate(false);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(true);
                progressDialog.show();

            }

            @Override
            protected void onProgressUpdate(Void... values) {
            }

            public String getAccessNumber(String b) {
                String balance = "";
                String currency = "USD";

                try {

                    balance = DownloadText(b).trim();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return balance;

            }

            String DownloadText(String URL) {
                int BUFFER_SIZE = 2000;
                InputStream in = null;
                try {
                    in = OpenHttpConnection(URL);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return "";
                }

                InputStreamReader isr = new InputStreamReader(in);
                int charRead;
                String str = "";
                char[] inputBuffer = new char[BUFFER_SIZE];
                try {
                    while ((charRead = isr.read(inputBuffer)) > 0) {

                        String readString = String.copyValueOf(inputBuffer, 0,
                                charRead);
                        str += readString;
                        inputBuffer = new char[BUFFER_SIZE];
                    }
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "";
                }

                return str;
            }

            InputStream OpenHttpConnection(String urlString) throws IOException {
                InputStream in = null;
                int response = -1;

                URL url = new URL(urlString);
                URLConnection conn = url.openConnection();

                if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");

                try {
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setAllowUserInteraction(false);
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect();
                    response = httpConn.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK) {
                        in = httpConn.getInputStream();
                    }
                } catch (Exception ex) {
                    throw new IOException("Error connecting");
                }
                return in;
            }

        }//end of webAccessNumber asynchronus

     public boolean onKeyDown(int keyCode, KeyEvent event)  
     {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
            {

                isOnline();

                return true;
            }

            return super.onKeyDown(keyCode, event);
        }

}

【问题讨论】:

  • getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); 您正在清除此处的首选项。为什么会在这里?
  • 您好,我已删除 clear() 。但在应用程序强制关闭或设备重启后仍然无法访问该值。就是这样。第一次启动设置页面打开(我在保存设置后发布代码的 BasePreferences 类视图将被更改为另一个包中的 DialerFragment 类只要应用程序运行,我就可以看到在这个类中显示的值。我正在访问这个类中的值方式 BasePreferences.savedBrand)
  • @abhi vinay,我也面临同样的问题。如果您有任何解决方案,请告诉我。

标签: java android sharedpreferences


【解决方案1】:

你不应该清除 onDestroy() 方法中的 SharedPreferences,因为当你再次运行你的活动或应用程序时,所有保存在首选项中的值和变量都会被删除,(就像你第一次安装你的应用程序一样)。

PS:这里有一个关于Using SharedPreferences and Storing Data in Android的教程

【讨论】:

  • 已添加评论 .. 已将其从 onDestroy 中删除,但仍无法访问
  • 在代码中的每一个地方,删除你清除 SharedPreferences.Editor 的所有行
  • 我做到了。我还在下面添加了从另一个类访问 sharedpreferences 值。SharedPreferences mySharedPreferences =this.getActivity().getSharedPreferences(myData, mode); String mybrand = mySharedPreferences.getString("brand", "");
【解决方案2】:

您正在清除代码中的首选项,

@Override
    protected void onDestroy() {
        //byMe


        super.onDestroy();

        //Preferences cleared
        getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
        saveArray(webArray);
    }

这是清除您的偏好。

【讨论】:

    【解决方案3】:

    您正在清除onDestroy 中的共享偏好:

    @Override
    protected void onDestroy() {
        //byMe
        super.onDestroy();
        getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); // <-- Remove this
        saveArray(webArray);
    }
    

    【讨论】:

      【解决方案4】:

      你删除它:

      @Override
      protected void onDestroy() {
      super.onDestroy();
      getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
      saveArray(webArray);
      }
      

      另见http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

      【讨论】:

      • 您好,我已删除..请查看我的评论以获得第一个答案“您好,我已删除 clear()。但在应用程序强制关闭或设备重启后仍无法访问该值。就是这样。第一次启动设置页面打开(我在保存设置后发布代码的 BasePreferences 类视图将被更改为另一个包中的 DialerFragment 类只要应用程序运行,我就可以看到这个 calss 中显示的值。我正在访问此类中的值以这种方式 BasePreferences.savedBrand)"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2017-08-18
      • 1970-01-01
      • 2011-04-03
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多