SharedPreferences用于保存用户配置文件

时间:2012-08-27 11:21:49

标签: android

我是SharedPreferences的新手。我想使用共享偏好保存用户个人资料,第二次用户进入个人资料活动时,他应该看到之前填写的详细信息。我怎么能这样做?你能给我一些代码吗?

这是我尝试的内容,但我不知道如果其他声明要放入内容:

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;

public class A extends Activity
{
   private static final String MY_KEY = "myprefs";
   private SharedPreferences myPrefs;
   private boolean loggedIn;

  protected void onCreate(Bundle savedInstanceState) 
  {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.iprofile);

   myPrefs = getSharedPreferences(MY_KEY, MODE_PRIVATE);

   loggedIn = myPrefs.getBoolean("loggedIn", false);  //default to false if the value has not been set

   if(loggedIn)
   {
      //do stuff

   }
  else
   {
       //do other stuff
    }
}
}

这是我的xml文件:http://pastebin.com/gXCHpk0E和我的java类:http://pastebin.com/NZJ0CR8H

3 个答案:

答案 0 :(得分:2)

让我们假设您有一个用户类,看起来像这样:

class User
{
    private String name;
    private String pass;
    private int age;

    public User(String name, String pass, int age)
    {
        this.name = name;
        ...
    }

    //getters and setters
}

您可以创建一个静态实用程序函数来读取或写入手机的SharedPreferences中的用户:

public class UserCreator
{
    public static User getUser(Context context)
    {
        SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);

        //Check if the user is already stored, if is, then simply get the data from
        //your SharedPreference object.

        boolean isValid = prefs.getBoolean("valid", false);

        if(isValid)
        {
            String user = prefs.getString("user", "");
            String pass = prefs.getString("pass", "");
            int age = prefs.getInt("age", 0); 
            ...
            return new User(user, pass, age); 
        }
        //If not, then store data
        else
        {
            //for example show a dialog here, where the user can log in.
            //when you have the data, then:

            if(...login successful...)
            {
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("user", "someusername");
                editor.putString("pass", "somepassword");
                editor.putInt("age", 20);
                editor.putBoolean("valid", true);
                ...
                editor.commit();
            }

            return getUser(context);
        }
    }
}

如果你有,那么你可以在你的活动中实际做到这一点(事实上你所有的活动):

User user = UserCreator.getUser(this);

如果存储了用户数据,则它将返回有效的用户对象。如果不是,它将询问用户,直到他/她输入可接受的数据,然后返回有效的用户对象。

答案 1 :(得分:0)

检查以下代码段:

  SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor prefsEditor = myPrefs.edit();
                prefsEditor.putString("user", edtsample.getEditableText().toString());
                prefsEditor.commit();

并且用于检索相同的用户和密码:

 SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    String prefName = myPrefs.getString("SRATE", "srate");

答案 2 :(得分:0)

您可以使用sharedpreferences和文本文件来执行此操作。 将配置文件的名称保存在文本文件中,将其余数据保存在该配置文件名称的共享首选项文件中。 以下是如何保存它的示例代码:

File f = new File("/data/data/<package name>/shared_prefs/"
            + profileName + ".xml");
if (f.exists()) {
    Toast.makeText(this, "Profile with that name already exists", Toast.LENGTH_SHORT).show();
} else {
    try {
        SharedPreferences sharedPreferences = this
            .getSharedPreferences(profileName,
                        Context.MODE_MULTI_PROCESS);
        Editor editor = sharedPreferences.edit();
        editor.putString("phn", phone_det.getText().toString()
                .trim());
        editor.putString("message", message_det.getText()
                    .toString());
        editor.putInt("Year", yrs);
        editor.putInt("Month", mon);
        editor.putInt("Day", da);
        editor.putInt("Hour", hr);
        editor.putInt("Minute", min);
        editor.commit();
        OutputStream outstream = this.openFileOutput(
                "Profiles.txt", Context.MODE_APPEND);
        // if file the available for reading
        OutputStreamWriter outputwriter = new OutputStreamWriter(
                    outstream);
        outputwriter.write(profileName);
        outputwriter.write('\r');
        outputwriter.write('\n');
        outputwriter.close();
    } catch (IOException e) {
        Toast.makeText(this,
        "Saving profile failed," + e.toString(),
        Toast.LENGTH_SHORT).show();
        }
    }

并打开它:

        try {
        // open the file for reading
        InputStream instream = openFileInput(
                "Profiles.txt");
        // if file the available for reading
        InputStreamReader inputreader = new InputStreamReader(instream);
        BufferedReader buffreader = new BufferedReader(inputreader);

        String profileName;

        // read every line of the file into the line-variable, on line at
        // the time
        while ((profileName = buffreader.readLine()) != null) {
            Profile objContact = new Profile();
            SharedPreferences sharedPreferences = getActivity()
                    .getSharedPreferences(profileName,
                            Context.MODE_MULTI_PROCESS);
            String phnno = sharedPreferences.getString("phn", "");
            String message = sharedPreferences.getString("message", "");
            String year = String.valueOf((sharedPreferences.getInt("Year",
                    0)));
            int month = (sharedPreferences.getInt("Month", 0));
            String day = String
                    .valueOf((sharedPreferences.getInt("Day", 0)));
            String hour = String.valueOf((sharedPreferences.getInt("Hour",
                    0)));
            String minute = String.valueOf((sharedPreferences.getInt(
                    "Minute", 0)));
            objContact.setName(line);
            objContact.setMessage(message);
            objContact.setDate(DateTime);
            objContact.setPhone(phnno);
            title.add(objContact);
        }
    } catch (java.io.FileNotFoundException e) {
        // do something if the myfilename.txt does not exits
    }