2014-09-26 56 views
0

我正在使用csipsimple代碼,並通過從webservice獲取json值來定製它以顯示品牌名稱。我使用SharedPreferences來存儲值。重啓後無法訪問另一個類中的SharedPreferences值

一旦應用程序強制關閉,或設備重新啓動SharedPreferences丟失。我使用提交併清除,但值仍爲空。

BasePrefsWizard負責拉網數據DialerFragment是其他類我打電話的名優產品類(它是在代碼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); 
     } 

} 
+1

'getSharedPreferences(WIZARD_PREF_NAME,MODE_PRIVATE).edit()清() .commit();'你在這裏清除偏好。這是爲什麼呢? – 2014-09-26 12:00:25

+0

嗨,我removee清除()。但在應用程序關閉或重新啓動設備後仍然無法訪問該值。這是如何。第一次啓動設置頁面打開(BasePreferences類,我保存設置後發佈代碼將視圖將更改哪個DialerFragment類在另一個包中只要應用程序運行,我可以看到在此calss顯示的值。我正在訪問此類中的值this方式BasePreferences.savedBrand) – 2014-09-27 05:41:44

+0

@ abhi vinay,我也面臨同樣的問題。如果你有任何解決方案,請讓我知道。 – 2014-11-24 10:53:41

回答

1

你不應該在的onDestroy清除SharedPreferences()方法,因爲當你再次運行你的活動或您的應用程序,所有保存的值和變量在首選項中被刪除,(就像你第一次安裝你的應用程序一樣)。

PS:這裏是一個教程約Using SharedPreferences and Storing Data in Android

+0

評論已添加..從onDestroy中刪除它,但仍然無法在代碼中的每個位置都訪問 – 2014-09-27 05:47:10

+0

,請刪除您清除SharedPreferences.Editor – Houcine 2014-09-27 13:01:22

+0

的所有行。我還在下面添加了從另一個類訪問sharedpreferences值.SharedPreferences mySharedPreferences = this.getActivity()。getSharedPreferences(myData, \t \t \t \t mode); \t String mybrand = mySharedPreferences.getString(「brand」,「」); – 2014-09-27 13:17:51

1

您清除在你的代碼你的喜好,

@Override 
    protected void onDestroy() { 
     //byMe 


     super.onDestroy(); 

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

這是清除您的偏好。

1

您清除共享prefereence在onDestroy

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

你刪除它。

@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

+0

嗨,我刪除了..請看看我對第一個答案的評論「你好我有removee清除(),但仍然無法訪問應用程序強制關閉或設備重新啓動後的值。啓動設置頁面打開(BasePreferences類,我保存設置後發佈的代碼將視圖更改其中的另一個DialerFragment類只要應用程序運行我可以看到在此calss展示的值。我正在訪問此類的價值這種方式BasePreferences.savedBrand)」 – 2014-09-27 05:46:12