我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
通过捆绑对象从此活动传递参数启动另一个活动
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
检索其他活动(YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
这适用于简单类型的数据类型。但如果您想在活动之间传递复杂的数据,则需要首先对其进行序列化。
这里有员工模型
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
您可以使用google提供的Gson-lib来序列化复杂的数据这样地
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);
其他回答
活动之间的数据传递主要通过意向对象进行。
首先,必须使用Bundle类将数据附加到intent对象。然后使用startActivity()或startActivityForResult()方法调用活动。
您可以从博客文章“将数据传递给活动”中找到更多信息。
我们可以通过两种方式将值传递给另一个Activity(已经发布了相同类型的答案,但我在这里发布了通过意图尝试的redcing代码)
1.通过意图
Activity1:
startActivity(new Intent(getApplicationContext(),Activity2.class).putExtra("title","values"));
InActivity 2:
String recString= getIntent().getStringExtra("title");
2.通过SharedPreference
Activity1:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
// 0 - for private mode
Editor editor = pref.edit();
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Activty2:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
pref.getString("key_name", null); // getting String
试试看:
当前活动.java
Intent intent = new Intent(currentActivity.this, TargetActivity.class);
intent.putExtra("booktype", "favourate");
startActivity(intent);
目标活动.java
Bundle b = getIntent().getExtras();
String typesofbook = b.getString("booktype");
您可以通过意图在两个活动之间进行沟通。每当您通过登录活动导航到任何其他活动时,都可以将sessionId设置为intent,并通过getIntent()在其他活动中获取。以下是代码段:
登录活动:
Intent intent = new Intent(YourLoginActivity.this,OtherActivity.class);
intent.putExtra("SESSION_ID",sessionId);
startActivity(intent);
finishAfterTransition();
其他活动:
在onCreate()中或需要它调用的任何位置getIntent().getStringExtra(“SESSION_ID”);此外,确保检查intent是否为空,并且在两个活动中传递的intent密钥应该相同。以下是完整的代码片段:
if(getIntent!=null && getIntent.getStringExtra("SESSION_ID")!=null){
sessionId = getIntent.getStringExtra("SESSION_ID");
}
但是,我建议您使用AppSharedPreferences存储sessionId,并在需要时从中获取。
标准方法。
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”);