我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
您可以尝试共享首选项,这可能是在活动之间共享数据的一个很好的选择
保存会话id-
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 i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);
现在,在第二个活动中,从捆绑包中检索数据:
获取捆绑包
Bundle bundle = getIntent().getExtras();
提取数据…
String stuff = bundle.getString(“stuff”);
在CurrentActivity.java中编写以下代码
Intent i = new Intent(CurrentActivity.this, SignOutActivity.class);
i.putExtra("SESSION_ID",sessionId);
startActivity(i);
按以下方式访问SignOutActivity.java中的SessionId
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_out);
Intent intent = getIntent();
// check intent is null or not
if(intent != null){
String sessionId = intent.getStringExtra("SESSION_ID");
Log.d("Session_id : " + sessionId);
}
else{
Toast.makeText(SignOutActivity.this, "Intent is null", Toast.LENGTH_SHORT).show();
}
}
我使用公共静态字段来存储活动之间的共享数据,但为了最大限度地减少其副作用,您可以:
只创建一个或尽可能少的字段,然后重用它们,使它们成为对象类型,并在接收活动中将其转换为所需类型。每当它们中的任何一个不再有用时,在下一次分配之前,将其显式设置为空,由垃圾收集器收集。
我在类中使用静态字段,并获取/设置它们:
喜欢:
public class Info
{
public static int ID = 0;
public static String NAME = "TEST";
}
要获取值,请在“活动”中使用:
Info.ID
Info.NAME
要设置值:
Info.ID = 5;
Info.NAME = "USER!";
使用捆绑包@链接https://medium.com/@nikhildhyani365/从一个活动到另一个活动的传递数据-18df2a701142//从介质复制
Intent I = new Intent(MainActivity.this,Show_Details.class);
Bundle b = new Bundle();
int x = Integer.parseInt(age.getText().toString());
int y = Integer.parseInt(className.getText().toString());
b.putString("Name",name.getText().toString());
b.putInt("Age",x);
b.putInt("ClassName",y);
I.putExtra("student",b);
startActivity(I);
使用Intent@链接https://android.jlelse.eu/passing-data-between-activities-using-intent-in-android-85cb097f3016