如何通过Intent将值传递给第三个活动?

时间:2016-05-06 09:30:25

标签: android android-intent

我需要将第一个活动的一些值传递给第三个活动。我已经将它从第1个传递到第2个。

我的第一个活动:(我在创建方法上做)

mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(DisplayRecepit.this, DisplayLogs.class);
    intent.putExtra("recepitID", receiptList.get(position).getId());
    startActivity(intent);
    }
});

我在第二个活动中收到了这样的话:(我在创建方法中做到了)

final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).execute();

现在我需要以某种方式将它从第二个活动传递到我的第三个活动。

在我的第二个活动中,我有一个按钮,可以将我带到第三个活动。

我在网上看到了一些示例,但我没有让我的应用运行,所以欢迎任何帮助。

问题: 我已经通过意图从第一个活动传递到第二个活动。 我应该如何将同样的值从第二个活动传递到第三个活动?

4 个答案:

答案 0 :(得分:0)

实际上它不可能直接从第一活动转到第三活动......

您必须遵循活动堆栈..

因此,如果您希望数据从第1个传递到第3个,请按照

进行操作

1st - &gt;第二 - &gt;第3次

答案 1 :(得分:0)

在您的第二个活动中使用意图传递此值

Intent i = new Intent(getApplicationContext, Third.class);
i.putExtra("forwardedId",forwardedId);
startActivity(i)

答案 2 :(得分:0)

首先,你必须将数据传递给第二个Activity.then你可以从第二个活动传递到第三个活动。

答案 3 :(得分:0)

使用默认的android机制是不可能的。如果你不能达到这个目的,你可以使用Eventbus :https://github.com/greenrobot/EventBus”在第一个活动中发布消息(可以是任何字符串,整数,甚至是带有arrylist的类pojo)并在任何地方捕获它。

转到上面提到的链接在应用级build.gradle中添加依赖项并同步它。

创建此事件Pojo:

    public class SomeEvent {
    private ArrayList<String> message;

    public SomeEvent(ArrayList<String> message) {
        this.message = message;
    }


    public ArrayList<String> getMessage() {
        return message;
    }

}

活动1:

onResume()中的

执行此操作:

EventBus.getDefault().register(this);
onDestroy()中的

执行此操作:

EventBus.getDefault().unregister(this);

发布活动:

仅在Eventbus注册后执行此操作。

EventBus.getDefault().post(new SomeEvent(some arraylist);

现在进入活动3:

只写这个方法。不要明确地调用它。 Eventbus在内部处理。确保此方法的参数是您在Eventbus中发布的事件类。

public void onEvent(SomeEvent event){
  // you got your arraylist which you posted from Activity 1;
  ArrayList<String> list = event.getMessage();
}