android - 如何在 sharedpreferences 中保存和检索多个值?

标签 android android-layout android-intent

我有 2 个 Activity 1.注册.java 2.SecureXActivity.java 在注册 Activity 中,我正在使用共享首选项注册我的应用程序。我使用共享首选项仅显示一次注册 Activity 。现在我的要求是 来自注册 Activity 的用户名将在注册时仅显示一次并将其保存在 SecureXActivity Activity 中,注册后只有此 Activity 对用户可见。那么请在这方面帮助我吗?我是安卓新手。

我的代码如下

注册.java

public class Register extends Activity
{
public static final String PREFS_NAME = "LoginPrefs";
public static final String USER_NAME = "USER";

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    /*
     * Check if we successfully logged in before.
     * If we did, redirect to home page
     */
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    if (settings.getString("logged", "").toString().equals("logged")) 
    {
        Intent intent = new Intent(Register.this, SecureXActivity.class);
        startActivity(intent);
    }

    Button b = (Button) findViewById(R.id.btnRegister);
    b.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View v) {
            EditText username = (EditText) findViewById(R.id.reg_employeeid);
            EditText password = (EditText) findViewById(R.id.reg_password);
            String welcm ="Welcome";
            String space = " ";
            EditText firstname = (EditText)findViewById(R.id.reg_firstname);
            EditText lastname = (EditText)findViewById(R.id.reg_lastname);
            String getfirstname = firstname.getText().toString();
            String getlasttname = lastname.getText().toString();
            String welcome=welcm.concat(space).concat(getfirstname).concat(space).concat(getlasttname);





            if(username.getText().toString().length() > 0 && password.getText().toString().length() > 0 ) 
            {
                if(username.getText().toString().equals("test") && password.getText().toString().equals("test")) 
                {
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("logged", "logged");
                    editor.commit();    
                    Intent intent = new Intent(Register.this, SecureXActivity.class);
                    intent.putExtra("name", welcome);
                    startActivity(intent);
                }
            }
        }
    });
}
} 

SecureXActivity.java

public void onCreate(Bundle savedInstanceState)
{
    Thread.setDefaultUncaughtExceptionHandler(new exceptionHandler(this));
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
        Bundle extras =getIntent().getExtras();

    if (extras != null)
    {
        String value = extras.getString("name");
        TextView txtwelcm= (TextView)findViewById(R.id.textViewwelcm);
        txtwelcm.setText(value);
    }
}

我想要从一个 Activity 到另一个 Activity 的值,并且该值应该保存到另一个 Activity 。在我上面的代码中,我已经使用 Intent 完成了这个。但问题是值(value)在第二个 Activity 中只显示一次。当我按下后退按钮或主页键时,值不可见?如何做到这一点。

为回应@Picarus 添加:

问题是我使用相同的共享首选项来仅显示一次注册 Activity 。 但它没有在 SecureX Activity 上显示名称。是否可以使用相同的共享首选项将值从注册 Activity 传递到安全 Activity

下面再次给出了完整的代码 注册.java

    public class Register extends Activity 
    { 
public static final String PREFS_NAME = "LoginPrefs"; 


@Override 
public void onCreate(Bundle savedInstanceState)  
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.register); 

    /* 
     * Check if we successfully logged in before. 
     * If we did, redirect to home page 
     */ 
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
    if (settings.getString("logged", "").toString().equals("logged"))  
    { 
        Intent intent = new Intent(Register.this, SecureXActivity.class); 
        startActivity(intent); 
    } 

    Button b = (Button) findViewById(R.id.btnRegister); 
    b.setOnClickListener(new OnClickListener()  
    { 
        public void onClick(View v) { 
            EditText username = (EditText) findViewById(R.id.reg_employeeid); 
            EditText password = (EditText) findViewById(R.id.reg_password); 
            String welcm ="Welcome"; 
            String space = " "; 
            EditText firstname = (EditText)findViewById(R.id.reg_firstname); 
            EditText lastname = (EditText)findViewById(R.id.reg_lastname); 
            String getfirstname = firstname.getText().toString(); 
            String getlasttname = lastname.getText().toString(); 
            String welcome=welcm.concat(space).concat(getfirstname).concat(space).concat(getlasttname); 





            if(username.getText().toString().length() > 0 && password.getText().toString().length() > 0 )  
            { 
                if(username.getText().toString().equals("test") && password.getText().toString().equals("test"))  
                { 
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
                    SharedPreferences.Editor editor = settings.edit(); 
                    editor.putString("name", welcome); 
                    editor.commit();     
                    Intent intent = new Intent(Register.this, SecureXActivity.class); 
                    //intent.putExtra("name", welcome); 
                    startActivity(intent); 
                } 
            } 
        } 
    }); 
} 
} 

SecureXActivity.java

public class SecureXActivity extends Activity 
{ 
public static final String PREFS_NAME = "LoginPrefs"; 

private ListView m_listview; 
Button btnSendlogs; 
Button btnMailadmin; 
Button btnContactSupport; 
Button btnSettings; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    Thread.setDefaultUncaughtExceptionHandler(new exceptionHandler(this)); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    //Here we are setting the installation date of a application 
    ContextWrapper context = this; 
    PackageManager packageManager = context.getPackageManager(); 
    ApplicationInfo appInfo; 
    try 
    { 
        appInfo = packageManager.getApplicationInfo("com.simsys.securex", 0); 
        String sourceDir= appInfo.sourceDir; 
        long dateTimeSync= new File(sourceDir).lastModified(); 
        String DateTimeStamp=getDate(dateTimeSync, "dd/MM/yyyy hh:mm:ss"); 
        String dateTimeSync2="Installed_Date:"; 
        String dateTimeSync3=dateTimeSync2.concat(DateTimeStamp); 
        TextView txtCurrentTime= (TextView)findViewById(R.id.textViewdatetime); 
        txtCurrentTime.setText(dateTimeSync3); 
    }  
    catch (NameNotFoundException e)  
    { 
        e.printStackTrace(); 
    } 
    //Here We Welcome the user 

    //List View 
    m_listview = (ListView) findViewById(R.id.list_view); 
    ArrayList<String> listItems=new ArrayList<String>(); 
    listItems.add("CAMERA"); 
    listItems.add("RECORDER"); 
    ArrayAdapter<String> adapter = 
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems); 

    m_listview.setAdapter(adapter); 
    if(isBluetoothServiceRunning()) 
    { 
        listItems.add("BLUETOOTH"); 
    } 
    if(isGprsServiceRunning()) 
    { 
        listItems.add("GPRS"); 
    } 
    if(isWifiServiceRunning()) 
    { 
        listItems.add("WIFI"); 
    } 
    adapter.notifyDataSetChanged(); 
    //Call to Buttons Functionality 
    btnSendlogs = (Button) findViewById(R.id.button_sendlogs); 
    btnSendlogs.setOnClickListener(myhandler1); 
    btnMailadmin=(Button) findViewById(R.id.button_mailtoadmin); 
    btnMailadmin.setOnClickListener(MailadminHandler); 
    btnContactSupport = (Button) findViewById(R.id.button_contactsupport); 
    btnContactSupport.setOnClickListener(ContactSupportHandler); 

} 

//Navigation from Registration to Main page 
public boolean onCreateOptionsMenu(Menu menu)  
{ 
    MenuInflater Inflater = getMenuInflater(); 
    Inflater.inflate(R.menu.menu, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    if (item.getItemId() == R.id.logout) 
    { 
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

        String data2=settings.getString("name", ""); 
        TextView txtwelcm= (TextView)findViewById(R.id.textViewwelcm); 
        txtwelcm.setText(data2); 
        SharedPreferences.Editor editor = settings.edit(); 
        editor.remove("name"); 
        editor.commit(); 
        finish(); 
    } 
    return super.onOptionsItemSelected(item); 
} 

最佳答案

要实现 sharedPreferences,请使用以下代码

 Sharedpreferences myPref = this.getSharedPreferneces("your_file_name",MODE);
 SharedPreferences.Editor editor = myPref.edit();
 editor.putString("String_Name",value);
 editor.putInt("Int_Name","value");

从 SharedPreferences 中检索

   Sharedpreferences myPref = this.getSharedPreferneces("your_file_name",MODE);  
   String stringValue = myPref.getStirng("String_Name","DEFAULT_VALUE");

关于android - 如何在 sharedpreferences 中保存和检索多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11756700/

相关文章:

Android:当 AudioManager 中的当前模式发生变化时得到通知

android - 无法验证自签名证书 - 找到 TrustAnchor 但证书验证失败

android - 有什么方法可以避免 Android XML 布局文件中的 "android:"语句?

java - Kotlin 编译库失败

android - 如何使android的数字编辑文本类似于DatePickerDialog上的向上/向下按钮?

android - 选择项目后,微调器在布局中向下移动

Android - 单选组按钮文本位置

android - 停止执行互联网 - 在应用程序子类中

android - 运行 Android 内存不足

android - 什么更快?一个 intent.putExtras(Bundle with Strings) 还是多个 intent.putExtra(String)?