【问题标题】:Android Studio - Getting preferences specifically for an accountAndroid Studio - 专门为帐户获取首选项
【发布时间】:2015-05-06 23:58:15
【问题描述】:

我正在创建一个应用程序,用户可以在其中注册一个帐户并继续使用该帐户登录。现在,当登录时,您有一些选项,包括您可以填写的一些编辑文本、一个复选框和一个搜索栏。

然而,这对我来说有点太复杂了。当我改变这些东西时,它们会保存。但他们通常会为应用程序保存。 我想要的是专门为用户帐户保存的这些首选项(ergo、复选框、编辑文本和搜索栏)。现在,不管你是什么账号,edittext上的文字都一样,seekbar上的进度一样,复选框也一样。

所以基本上,我想要帐户特定的偏好。但我不知道如何实现这一目标。 提前致谢。

编辑:

这是用户设置的代码。它是一个使用多个小东西(如按钮和edittextst)的tabhost。现在我只使用 sharedpreferences 来保存对edittext、复选框和按钮所做的更改。图片尚未保存(我正在尝试修复的其他问题)。

公共类 SettingsActivity 扩展 ActionBarActivity 实现 View.OnClickListener {

CheckBox notificationsCheckbox;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;

TextView username;
TextView phone;
TextView address;
ImageView accountImage;

public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Street = "addressKey";

SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.activity_settings);
    TabHost tabHost = (TabHost) findViewById(R.id.settingsTabhost);
    setTitle("Settings");

    tabHost.setup();

    TabHost.TabSpec tabSpec = tabHost.newTabSpec("General Settings");
    tabSpec.setContent(R.id.firstTab);
    tabSpec.setIndicator("General Settings");
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("Account Settings");
    tabSpec.setContent(R.id.secondTab);
    tabSpec.setIndicator("Account Settings");
    tabHost.addTab(tabSpec);

    username = (TextView) findViewById(R.id.editText);
    phone = (TextView) findViewById(R.id.editText2);
    address = (TextView) findViewById(R.id.editText3);
    accountImage = (ImageView) findViewById(R.id.userPicture);

    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    if (sharedpreferences.contains(Name))
    {
        username.setText(sharedpreferences.getString(Name, ""));

    }
    if (sharedpreferences.contains(Phone))
    {
        phone.setText(sharedpreferences.getString(Phone, ""));

    }
    if (sharedpreferences.contains(Street))
    {
        address.setText(sharedpreferences.getString(Street, ""));

    }

    Button imageButton = (Button) findViewById(R.id.pictureButton);
    imageButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 1);
        }
    });

    Button bluetoothSettingsButton = (Button) findViewById(R.id.bluetoothBtn);

    bluetoothSettingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent (SettingsActivity.this, DeviceScanActivity.class));
        }
    });

    volumeSeekbar = (SeekBar) findViewById(R.id.seekBar);
    volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
            loadSavedSlider();
        }
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            // TODO Auto-generated method stub
            saveSlidePreferences();



        }
    });
    seekbarVolume();

    notificationsCheckbox = (CheckBox) findViewById(R.id.notifCheckbox);
    notificationsCheckbox.setOnClickListener(this);
    loadSavedCheckbox();
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.userPicture);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
}

public void run(View view){
    String n  = username.getText().toString();
    String ph  = phone.getText().toString();
    String s  = address.getText().toString();

    SharedPreferences.Editor editor = sharedpreferences.edit();

    editor.putString(Name, n);
    editor.putString(Phone, ph);
    editor.putString(Street, s);

    editor.commit();

    Toast.makeText(getBaseContext(), "Saved",
            Toast.LENGTH_SHORT).show();
}

private void loadSavedCheckbox() {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);



    if (checkBoxValue) {
        notificationsCheckbox.setChecked(true);

    }
    else {
        notificationsCheckbox.setChecked(false);

    }
}

private void loadSavedSlider() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    int mProgress = sharedPreferences.getInt("mMySeekBarProgress", 0);
    volumeSeekbar.setProgress(mProgress);
}

private void savePreferences(String key, boolean value) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);

    editor.commit();

}

private void seekbarVolume() {
    try {
        volumeSeekbar = (SeekBar) findViewById(R.id.seekBar);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        volumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        volumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));


        volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

private void saveSlidePreferences() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    int mProgress = volumeSeekbar.getProgress();
    editor.putInt("mMySeekBarProgress", mProgress).commit();


    editor.commit();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_settings, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }


    return super.onOptionsItemSelected(item);
}

// here we tell the app to simply save the preferences of the notifications checkbox.
public void onClick(View v) {
    // TODO Auto-generated method stub
    savePreferences("CheckBox_Value", notificationsCheckbox.isChecked());

    if (notificationsCheckbox.isChecked()){

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setAutoCancel(true);
        builder.setContentTitle("Findr");
        builder.setContentText("Notifications Activated");
        builder.setSmallIcon(R.drawable.ic_launcher);

        Notification notification = builder.build();
        NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
        manager.notify(8, notification);
    }
    else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setAutoCancel(true);
        builder.setContentTitle("Findr");
        builder.setContentText("Notifications Deactivated");
        builder.setSmallIcon(R.drawable.ic_launcher);

        Notification notification = builder.build();
        NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
        manager.notify(8, notification);
    }
}

}

【问题讨论】:

  • 您可以将用户名附加到用于保存和检索每个首选项的密钥中。
  • @DanielNugent 谢谢你的回答。但是,我不确定我该怎么做。你有类似的例子吗?
  • 这只是我的一个想法,我没有看到示例。您可以将代码发布到您当前保存和检索首选项的位置吗?
  • @DanielNugent 你去吧,我希望它不会太过分。它利用标签主机将“常规设置”与“帐户设置”分开。在常规设置中,有一个用于访问蓝牙活动的按钮、一个用于通知的复选框和一个什么都不做的搜索栏。至于帐户选项:它包含 3 个编辑文本,分别是用户名、电话和地址。它还包含一个可单击按钮,可将按钮上方显示的图片更改为您从图库中选择的任何内容。我的意图是让这些选项专属于每个帐户。

标签: android login save settings


【解决方案1】:

这只是一个关于如何实现所需结果的想法。

首先,创建一个实例变量来存储当前用户名:

String uName;

我相信你会把它设置在这里:

public void run(View view){
    String n  = username.getText().toString();
    uName = n;
    //.......

然后,每当您设置或检索首选项时,将uName 附加到密钥。这样一来,所使用的首选项对每个用户都是唯一的。

例子:

public void run(View view){
    String n  = username.getText().toString();
    uName = n; //added
    String ph  = phone.getText().toString();
    String s  = address.getText().toString();

    SharedPreferences.Editor editor = sharedpreferences.edit();

    editor.putString(uName + Name, n); //modified
    editor.putString(uName + Phone, ph); //modified
    editor.putString(uName + Street, s); //modified

    editor.commit();

    Toast.makeText(getBaseContext(), "Saved",
            Toast.LENGTH_SHORT).show();
}

private void loadSavedCheckbox() {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean checkBoxValue = sharedPreferences.getBoolean(uName + "CheckBox_Value", false); //modified

    if (checkBoxValue) {
        notificationsCheckbox.setChecked(true);

    }
    else {
        notificationsCheckbox.setChecked(false);

    }
}

private void loadSavedSlider() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    int mProgress = sharedPreferences.getInt(uName + "mMySeekBarProgress", 0); //modified
    volumeSeekbar.setProgress(mProgress);
}

private void savePreferences(String key, boolean value) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(uName + key, value); //modified

    editor.commit();

}

这里:

    private void saveSlidePreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        int mProgress = volumeSeekbar.getProgress();
        editor.putInt(uName + "mMySeekBarProgress", mProgress).commit(); //modified


        editor.commit();
  }

【讨论】:

  • 谢谢你,我认为我已经接近了,但它还没有完全正常工作。我应该提到的是用户使用他们的电子邮件而不是用户名登录。所以现在我用提供的代码没有得到任何结果。用户的电子邮件被输入一个editText,然后用户也输入他们的密码。当他们登录时,需要某种代码将输入的电子邮件从 loginActivity 传递到 mainActivity,然后再传递到 settingsActivity(因为当你进入时,你首先进入主活动屏幕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多