Android SharedPreferences not loading and saving properly

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 06:55:47

问题


I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.

My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.

Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.

public SharedPreferences sp;
public Editor e;

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);


    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();


      e.putString("intro", introstring);
      e.commit(); // you forgot to commit


  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit(); 
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit(); 
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit(); 
  }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.settingmenu);

    //SP
    sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
    // named preferences - get the default ones and finish with it
    e = sp.edit();

    Button tt = (Button)findViewById(R.id.savebutton);
    tt.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) {
                finish();

        }
    });


public void save(View view)
{
    //THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
    savethethings();

    this.finish();
    return;
}

public String finishedtext(String userstring)
{

    smsintroduction = (sp.getString("intro", ""));
    smsbody = (sp.getString("body", ""));
    checkboxtext = (sp.getString("checkbody", ""));
    checkboxmessage = (sp.getString("checkboxdescr", ""));

    if(smsintroduction.isEmpty()) 
    {
        if(smsbody.isEmpty())
        {
            if(checkboxtext.isEmpty())

            {
                if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
                {
                    //Essentially the DEFAULT if they're ALL null
                    smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
                }
            }
        }
    }




    Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();

    String thetext = "";

    thetext = smsintroduction + " " + smsbody + " " + checkboxtext;

    return thetext;
}

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);


    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();

  //      if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
  //      {
      e.putString("intro", introstring);
      e.commit(); // you forgot to commit


  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit(); 
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit(); 
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit(); 
  }
}

回答1:


Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values. Sample code given below.

public class SessionManager {         
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;    
int PRIVATE_MODE = 0;

public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
    editor = pref.edit();
    editor.apply();
}

public void setIntroMessage(String data) {
    editor.putString("intro", data);
    editor.commit();        
}   

public String getIntroMessage() {
    return pref.getString("intro", null);
} 

}



来源:https://stackoverflow.com/questions/22154756/android-sharedpreferences-not-loading-and-saving-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!