如何在Android应用程序中的活动之间传递数据?

如何在Android应用程序中的活动之间传递数据?,android,android-intent,android-activity,Android,Android Intent,Android Activity,我有一个场景,在通过登录页面登录后,每个活动上都会有一个注销按钮 单击“注销”,我将传递要注销的已登录用户的会话id。有谁能指导我如何让所有活动都能使用会话id 此情况的任何替代方法都是将会话id传递给用于启动活动的Intent中的注销活动: Intent intent = new Intent(getBaseContext(), SignoutActivity.class); intent.putExtra("EXTRA_SESSION_ID", sessionId); startActivi

我有一个场景,在通过登录页面登录后,每个
活动上都会有一个注销
按钮

单击“注销”
,我将传递要注销的已登录用户的会话id。有谁能指导我如何让所有
活动都能使用
会话id


此情况的任何替代方法都是将会话id传递给用于启动活动的
Intent
中的注销活动:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
  if (getIntent().getExtras() != null) {
      String value = getIntent().getStringExtra("key");
      //The key argument must always match that used send and retrive value from one activity to another.
  }
  if (getIntent().getExtras() != null) {
      Bundle bundle = getIntent().getStringExtra("bundle_key");    
      String value = bundle.getString("key");
      //The key argument must always match that used send and retrive value from one activity to another.
  }
在下一个活动中访问该意图:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
  if (getIntent().getExtras() != null) {
      String value = getIntent().getStringExtra("key");
      //The key argument must always match that used send and retrive value from one activity to another.
  }
  if (getIntent().getExtras() != null) {
      Bundle bundle = getIntent().getStringExtra("bundle_key");    
      String value = bundle.getString("key");
      //The key argument must always match that used send and retrive value from one activity to another.
  }

for Intents提供了更多信息(请参阅标题为“额外服务”的部分)。

尝试执行以下操作:

IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
创建一个简单的“helper”类(工厂供您选择),如下所示:

import android.content.Intent;

public class IntentHelper {
    public static final Intent createYourSpecialIntent(Intent src) {
          return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
    }
}
IntentHelper.createYourSpecialIntent(getIntent());
这将是你想要的工厂。每当您需要一个新的意图时,请在intentelper中创建一个静态工厂方法。要创建一个新的意图,您应该这样说:

import android.content.Intent;

public class IntentHelper {
    public static final Intent createYourSpecialIntent(Intent src) {
          return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
    }
}
IntentHelper.createYourSpecialIntent(getIntent());
在你的活动中。当您想在“会话”中“保存”某些数据时,只需使用以下命令:

IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
并发送此意图。在目标活动中,您的字段将可用为:

getIntent().getStringExtra("YOUR_FIELD_NAME");
所以现在我们可以像旧会话一样使用意图(比如在servlet或中)。

正如Erich所指出的,传递额外内容是一种很好的方法

不过,对象是另一种方式,当跨多个活动处理同一状态(而不是必须到处获取/放置)或比原语和字符串更复杂的对象时,有时更容易处理

您可以扩展应用程序,然后在其中设置/获取您想要的任何内容,并使用从任何活动(在同一应用程序中)访问它


还请记住,您可能看到的其他方法,如静力学,可能会有问题,因为它们都是静态的。应用程序也有助于解决这个问题。

更新了注意我提到的使用。它有一个简单的API,可以跨应用程序的活动进行访问。但这是一个笨拙的解决方案,如果您传递敏感数据,则会带来安全风险。最好使用意图。它有一个广泛的重载方法列表,可用于在活动之间更好地传输许多不同的数据类型。看一看。这很好地展示了putExtra的使用

在活动之间传递数据时,我首选的方法是为相关活动创建一个静态方法,其中包括启动意图所需的参数。这样就可以方便地设置和检索参数。所以它可以看起来像这样

public class MyActivity extends Activity {
    public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
    Intent intent = new Intent(from, MyActivity.class);
        intent.putExtra(ARG_PARAM1, param1);
        intent.putExtra(ARG_PARAM2, param2);
        return intent;
}

....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            }.getType();
            Employee selectedEmp = gson.fromJson(empStr, type);

然后,您可以为预期的活动创建意图,并确保您拥有所有参数。您可以对片段进行调整,以使其适应。上面是一个简单的例子,但你明白了。

在你当前的活动中,创建一个新的
Intent

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("key",value);
startActivity(i);
然后在新活动中,检索这些值:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}

使用此技术将变量从一个活动传递到另一个活动。

在活动之间传递数据最方便的方法是传递意图。在要从中发送数据的第一个活动中,应添加代码

String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);
您还应该导入

import android.content.Intent;
然后在下一个Acitvity(SecondActivity)中,您应该使用以下代码从intent检索数据

String name = this.getIntent().getStringExtra("name");

另一种方法是使用存储数据的公共静态字段,即:

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...

活动之间的数据传递主要通过意图对象进行

首先,您必须使用
Bundle
类将数据附加到intent对象。然后使用
startActivity()
startActivityForResult()
方法调用活动

你可以通过博客文章中的一个例子找到更多关于它的信息。

我最近发布了一个jQuery风格的Android框架,它使所有类似的任务变得更简单。如前所述,
SharedReferences
是实现这一点的一种方法

是作为单例实现的,因此这是一个选项,在Vapor API中,它有一个重载严重的
.put(…)
方法,因此您不必显式地担心正在提交的数据类型,只要支持它。它也很流畅,因此您可以链接调用:

$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
它还可以选择自动保存更改,并在后台统一读写过程,因此您不需要像在标准Android中那样显式检索编辑器

或者,您可以使用
意图
。在Vapor API中,您还可以使用可链接的重载
.put(…)
方法:

如其他答案中所述,将其作为额外信息传递。您可以从
活动
中检索额外内容,此外,如果您正在使用,这将自动为您完成,以便您可以使用:

this.extras()
要在切换到的
活动
的另一端检索它们


希望这是一些人感兴趣的:)

你只需在打电话时发送额外信息即可

像这样:

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
现在,在您的
SecondActivity
OnCreate
方法中,您可以像这样获取额外的内容

如果您发送的值为长
格式

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
如果发送的值是
字符串

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
如果发送的值是
布尔值

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);

我在类中使用静态字段,并获取/设置它们:

比如:

要获取值,请在活动中使用:

Info.ID
Info.NAME
Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
String str= getIntent().getStringExtra("Variable name which you sent as an extra");
要设置值,请执行以下操作:

Info.ID = 5;
Info.NAME = "USER!";
源类:

Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
目标类(新活动类):

您可以在另一个活动中检索它。两种方式:

int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
第二种方式是:

Intent i = getIntent();
String name = i.getStringExtra("name");

您可以使用
SharedReferences

  • 日志记录。
    SharedReferences

    SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("sessionId", sessionId);
    editor.commit();
    
  • 签出。SharedReferences中的时间获取会话id

    SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    
  • 如果您没有所需的会话id,请删除SharedReferences:

    SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
    settings.edit().clear().commit();
    
    这是非常有用的,因为有一次您保存了值,然后检索anyw
    byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    
    Intent intent = new Intent(getBaseContext(), NextActivity.class);
    Foo foo = new Foo();
    intent.putExtra("foo", foo);
    startActivity(intent);
    
    Foo foo = getIntent().getExtras().getParcelable("foo");
    
     int n= 10;
     Intent in = new Intent(From_Activity.this,To_Activity.class);
     Bundle b1 = new Bundle();
     b1.putInt("integerNumber",n);
     in.putExtras(b1);
     startActivity(in);
    
     Bundle b2 = getIntent().getExtras();
     int m = 0;
     if(b2 != null)
      {
         m = b2.getInt("integerNumber");
      }
    
    public class HomeIntent extends Intent {
    
        private static final String ACTION_LOGIN = "action_login";
        private static final String ACTION_LOGOUT = "action_logout";
    
        private static final String ARG_USERNAME = "arg_username";
        private static final String ARG_PASSWORD = "arg_password";
    
    
        public HomeIntent(Context ctx, boolean isLogIn) {
            this(ctx);
            //set action type
            setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
        }
    
        public HomeIntent(Context ctx) {
            super(ctx, HomeActivity.class);
        }
    
        //This will be needed for receiving data
        public HomeIntent(Intent intent) {
            super(intent);
        }
    
        public void setData(String userName, String password) {
            putExtra(ARG_USERNAME, userName);
            putExtra(ARG_PASSWORD, password);
        }
    
        public String getUsername() {
            return getStringExtra(ARG_USERNAME);
        }
    
        public String getPassword() {
            return getStringExtra(ARG_PASSWORD);
        }
    
        //To separate the params is for which action, we should create action
        public boolean isActionLogIn() {
            return getAction().equals(ACTION_LOGIN);
        }
    
        public boolean isActionLogOut() {
            return getAction().equals(ACTION_LOGOUT);
        }
    }
    
    public class LoginActivity extends AppCompatActivity {
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            String username = "phearum";
            String password = "pwd1133";
            final boolean isActionLogin = true;
            //Passing data to HomeActivity
            final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
            homeIntent.setData(username, password);
            startActivity(homeIntent);
    
        }
    }
    
    public class HomeActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
    
            //This is how we receive the data from LoginActivity
            //Make sure you pass getIntent() to the HomeIntent constructor
            final HomeIntent homeIntent = new HomeIntent(getIntent());
            Log.d("HomeActivity", "Is action login?  " + homeIntent.isActionLogIn());
            Log.d("HomeActivity", "username: " + homeIntent.getUsername());
            Log.d("HomeActivity", "password: " + homeIntent.getPassword());
        }
    }
    
    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(Intent.EXTRA_TEXT, "my text");
    startActivity(intent);
    
    Intent intent = getIntent();
    String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);
    
    static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";
    
    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(EXTRA_STUFF, "my text");
    startActivity(intent);
    
    Intent intent = getIntent();
    String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);
    
     <string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>
    
    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
    startActivity(intent);
    
    Intent intent = getIntent();
    String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
    
    Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
    mIntent.putExtra("data", data);
    startActivity(mIntent);
    
    public class DataHolder {
    
     private static DataHolder dataHolder;
     private List<Model> dataList;
    
     public void setDataList(List<Model>dataList) {
        this.dataList = dataList;
     }
    
     public List<Model> getDataList() {
        return dataList;
     }
    
     public synchronized static DataHolder getInstance() {
        if (dataHolder == null) {
           dataHolder = new DataHolder();
        }
        return dataHolder;
     }
    }
    
    private List<Model> dataList = new ArrayList<>();
    DataHolder.getInstance().setDataList(dataList);
    
    private List<Model> dataList = DataHolder.getInstance().getDataList();
    
    SharedPreferences pref = myContexy.getSharedPreferences("Session 
    Data",MODE_PRIVATE);
    SharedPreferences.Editor edit = pref.edit();
    edit.putInt("Session ID", session_id);
    edit.commit();
    
    SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
    session_id = pref.getInt("Session ID", 0);
    
    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("USER_NAME", "xyz@gmail.com");
    startActivity(intent);
    
    String s = getIntent().getStringExtra("USER_NAME");
    
    class Employee{
        private String empId;
        private int age;
        print Double salary;
    
        getters...
        setters...
    }
    
    String strEmp = new Gson().toJson(emp);
    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("EMP", strEmp);
    startActivity(intent);
    
    Bundle bundle = getIntent().getExtras();
    String empStr = bundle.getString("EMP");
                Gson gson = new Gson();
                Type type = new TypeToken<Employee>() {
                }.getType();
                Employee selectedEmp = gson.fromJson(empStr, type);
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // "Go to Second Activity" button click
        public void onButtonClick(View view) {
    
            // get the text to pass
            EditText editText = (EditText) findViewById(R.id.editText);
            String textToPass = editText.getText().toString();
    
            // start the SecondActivity
            Intent intent = new Intent(this, SecondActivity.class);
            intent.putExtra(Intent.EXTRA_TEXT, textToPass);
            startActivity(intent);
        }
    }
    
    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            // get the text from MainActivity
            Intent intent = getIntent();
            String text = intent.getStringExtra(Intent.EXTRA_TEXT);
    
            // use the text in a TextView
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText(text);
        }
    }
    
    public class MainActivity extends AppCompatActivity {
    
        private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // "Go to Second Activity" button click
        public void onButtonClick(View view) {
    
            // Start the SecondActivity
            Intent intent = new Intent(this, SecondActivity.class);
            startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
        }
    
        // This method is called when the second activity finishes
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            // check that it is the SecondActivity with an OK result
            if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
                if (resultCode == RESULT_OK) {
    
                    // get String data from Intent
                    String returnString = data.getStringExtra(Intent.EXTRA_TEXT);
    
                    // set text view with string
                    TextView textView = (TextView) findViewById(R.id.textView);
                    textView.setText(returnString);
                }
            }
        }
    }
    
    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
        }
    
        // "Send text back" button click
        public void onButtonClick(View view) {
    
            // get the text from the EditText
            EditText editText = (EditText) findViewById(R.id.editText);
            String stringToPassBack = editText.getText().toString();
    
            // put the String to pass back into an Intent and close this activity
            Intent intent = new Intent();
            intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
    
    Intent intent = new Intent(getApplicationContext(), ClassName.class);
    intent.putExtra("Variable name", "Value you want to pass");
    startActivity(intent);
    
    String str= getIntent().getStringExtra("Variable name which you sent as an extra");
    
    val intent = Intent(this, SecondActivity::class.java)
    intent.putExtra("key", "value")
    startActivity(intent)
    
    val value = intent.getStringExtra("key")
    
    companion object {
        val KEY = "key"
    }
    
      String value="xyz";
      Intent intent = new Intent(CurrentActivity.this, NextActivity.class);    
      intent.putExtra("key", value);
      startActivity(intent);
    
      if (getIntent().getExtras() != null) {
          String value = getIntent().getStringExtra("key");
          //The key argument must always match that used send and retrive value from one activity to another.
      }
    
      String value="xyz";
      Intent intent = new Intent(CurrentActivity.this, NextActivity.class);  
      Bundle bundle = new Bundle();
      bundle.putInt("key", value);  
      intent.putExtra("bundle_key", bundle);
      startActivity(intent);
    
      if (getIntent().getExtras() != null) {
          Bundle bundle = getIntent().getStringExtra("bundle_key");    
          String value = bundle.getString("key");
          //The key argument must always match that used send and retrive value from one activity to another.
      }