【问题标题】:How to pass sharedpreferences from one activity to another activity?如何将共享首选项从一项活动传递到另一项活动?
【发布时间】:2019-03-22 13:17:24
【问题描述】:

我的项目中有两个活动,一个是 MainActivity,另一个是 Main2activity,在 Main2activity 中,我从用户那里获取输入并将其存储在 SharedPreference 中,现在我想将此数据传递给 MainActivity 并将该数据显示给用户。

Main2activity的代码是

 package com.example.to_doapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {




public void BackMain ( View view )
{
    Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) ;
    SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
    EditText editText = ( EditText) findViewById( R.id.editText3) ;
    String s = editText.getText().toString();
    sharedPreferences.edit().putString("task" , s ) .apply();

    //intent.putStringArrayListExtra("key",arr);
    startActivity(intent);



}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

}

代码敌人 Mainactivity 是

package com.example.to_doapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


public void onclick (View view){

    Intent intent = new Intent(getApplicationContext(), Main2Activity.class );
    startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Intent intent = getIntent();


 }

@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_main, 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);
}

}

我想知道如何传递共享首选项以及如何在列表视图中向用户显示该数据。 提前感谢您的帮助。

【问题讨论】:

  • 无需将 SharedPreference 从一个屏幕传递到另一个屏幕,因为您可以通过按键从应用程序的任何位置访问 SharedPreference 对象。
  • @RutvikBhatt 请详细说明!!由于我是新手,我无法理解。
  • @swati 我听不懂!!​​span>

标签: android android-intent sharedpreferences


【解决方案1】:

您可以在第二个活动中使用SharedPreferences getString() 方法。 这是文档:https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

【讨论】:

    【解决方案2】:
    SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
    sharedPreferences.getString("task", "");
    

    您可以随时使用上述代码从共享偏好中获取数据,直到它被清除。 但我建议你为它创建一个类并在同一类中执行所有与偏好相关的任务

    【讨论】:

    • Shahnavaz ,您的意思是说我将这段代码添加到我的 MainActivity 以访问存储在 sharedpreferences 中的数据。在此之后我如何向用户显示这些数据!
    • 是的,取决于你想如何显示它。您可以使用 Toast.makeText(this,"This is your data" + task,Toast.LENGTH_SHORT).show();或者你可以使用 TextView 来显示它link
    【解决方案3】:

    最简单的方法是:

    设置 SharedPref:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    Editor editor = prefs.edit();
    editor.putString(PREF_NAME, "someValue");
    editor.commit();
    

    获取 SharedPref:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    String yourValue = prefs.getString(PREF_NAME, "");
    

    【讨论】:

    • 如果我们的 sharedpreferences 包含多个数据怎么办,那么 yourValue 中的字符串是什么?基本上,我想知道 prefs.getString(PREF_NAME, "") 是如何工作的
    【解决方案4】:

    无需传递 SharedPreferences 。您会在 SharedPreferences 值上获得任何活动或片段..

    SharedPreferences shared = getSharedPreferences("Your SharedPreferences name", MODE_PRIVATE);
    String data= shared.getString("key", "");
    

    注意:key应与编辑或保存数据时间使用相同。还有 SharedPreferences 名称 相同的。

    【讨论】:

    • 如何将其中存储的数据显示给用户请指定!!
    • 你可以显示任何视图控件。
    【解决方案5】:

    当您为应用添加共享偏好时,可以从应用内的任何位置访问它。

    SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
    String data= shared.getString("nameOfValue", "");
    

    【讨论】:

      【解决方案6】:

      我正在与您分享设置和获取sharedpreference 数据的最简单方法:

      首先像这样为Shared Preference 开设一个课程:

      public class MySharedPreferences {
      
      private static String MY_PREFS = "MyPrefs";
      private static String IS_LOGGED_IN = "is_logged_in";
      private static String USERNAME_ID = "username"
      
      public static MySharedPreferences instance;
      private Context context;
      private SharedPreferences sharedPreferences;
      private SharedPreferences.Editor editor;
      
      
      public static MySharedPreferences getInstance(Context context) {
          if (instance == null)
              instance = new MySharedPreferences(context);
          return instance;
      }
      
      private MySharedPreferences(Context context) {
          this.context = context;
          sharedPreferences = context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
          editor = sharedPreferences.edit();
      }
      
      public void deleteAllSharePrefs(Context context){
          this.context = context;
          sharedPreferences = context.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
          editor.clear().commit();
      }
      
      public Boolean getIsLoggedIn(boolean b) {
          return sharedPreferences.getBoolean(IS_LOGGED_IN, false);
      }
      
      public void setIsLoggedIn(Boolean isLoggedIn) {
          editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
          editor.commit();
      }
      
      
      public String getUsername() {
          return sharedPreferences.getString(USERNAME_ID, "");
      }
      
      public void setUsername(String username) {
          editor.putString(USERNAME_ID, username);
          editor.commit();
      }
      

      然后你想在哪里设置 SharedPreference :

      public void BackMain ( View view ){
      EditText editText = ( EditText) findViewById( R.id.editText3) ;
      MySharedPreferences.getInstance(Main2Activity.this).setUsername(editText.getText().toString());
      Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) 
      startActivity(intent);
      }
      

      现在,在您的第二个活动中获取 SharedPreference:

      MySharedPreferences.getInstance(ACTIVITYNAME.this).getUsername();
      

      或在片段中:

      MySharedPreferences.getInstance(getActivity()).getUsername();
      

      或在适配器中:

      MySharedPreferences.getInstance(context).getUsername();
      

      【讨论】:

      • 在哪里添加此类 sharedpreferences 以及如何将其显示给用户?
      • @shalininegi 我认为你是 Android 新手,请在你的主包中创建这个类
      猜你喜欢
      • 2014-09-19
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多