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

单击注销时,我将传递要注销的登录用户的会话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);

其他回答

使用全局类:

public class GlobalClass extends Application
{
    private float vitamin_a;


    public float getVitaminA() {
        return vitamin_a;
    }

    public void setVitaminA(float vitamin_a) {
        this.vitamin_a = vitamin_a;
    }
}

您可以从所有其他类调用该类的setter和getter。要做到这一点,您需要在每个活动中创建一个GlobalClass对象:

GlobalClass gc = (GlobalClass) getApplication();

然后,您可以调用例如:

gc.getVitaminA()
/*
 * If you are from transferring data from one class that doesn't
 * extend Activity, then you need to do something like this.
 */ 

public class abc {
    Context context;

    public abc(Context context) {
        this.context = context;
    }

    public void something() {
        context.startactivity(new Intent(context, anyone.class).putextra("key", value));
    }
}

科特林

从第一个活动传递

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

参加第二项活动

val value = intent.getStringExtra("key")

建议

始终将密钥放在常量文件中,以便于管理。

companion object {
    val KEY = "key"
}

第一项活动:

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");

尝试执行以下操作:

创建一个简单的“助手”类(意图工厂),如下所示:

import android.content.Intent;

public class IntentHelper {
    public static final Intent createYourSpecialIntent(Intent src) {
          return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
    }
}

这将是你所有意图的工厂。每次需要一个新的Intent时,在IntentHelper中创建一个静态工厂方法。要创建新的意向,您应该这样说:

IntentHelper.createYourSpecialIntent(getIntent());

在您的活动中。当您想在“会话”中“保存”某些数据时,只需使用以下方法:

IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);

并发送此意向。在目标“活动”中,您的字段将显示为:

getIntent().getStringExtra("YOUR_FIELD_NAME");

所以现在我们可以像旧会话一样使用Intent(如servlet或JSP)。