1

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

这是我尝试过的,但我不知道在 if else 语句中放什么:

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

4

3 回答 3

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);

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

于 2012-08-27T11:38:57.720 回答
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");
于 2012-08-27T13:14:45.783 回答
0

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

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
    }
于 2015-11-09T07:10:22.760 回答