简体   繁体   English

无法将数据从活动传递到片段

[英]Can't pass data from activity to fragment

I have a problem with pass data from activity to fragment, it says null pointer exception, but my data is not null.我在将数据从活动传递到片段时遇到问题,它表示空指针异常,但我的数据不为空。

This is my activity :这是我的活动:

@Override
public void onResponse(Call call, Response response) throws IOException {
    dataj = response.body().string();
    System.out.println(dataj);
    Bundle bundle = new Bundle();
    bundle.putString("datak", dataj);
    FragmentUtama fu = new FragmentUtama();
    fu.setArguments(bundle);
    Intent load = new Intent(LoginActivity.this, MainActivity.class);
    load.putExtra("datajs", dataj);
    startActivity(load);
    finish();
}

and this is my fragment :这是我的片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        String datas = getArguments().getString("datak");
        System.out.println(datas);
        return inflater.inflate(R.layout.fragment_utama, container, false);
}

Thanks for your help.谢谢你的帮助。

You don't pass data to fragment via Intents.您不会通过 Intent 将数据传递给片段。 Arguments are passed by setting them to the fragment instance before calling Fragment transaction commit.在调用 Fragment 事务提交之前,通过将参数设置到片段实例来传递参数。

SomeFragment f = new SomeFragment ();
// Supply data input as an argument.
Bundle args = new Bundle();
args.putInt("some_key", value);
f.setArguments(args);

then you read it in your fragment.然后你在你的片段中阅读它。

NOTE: setArguments can only be called before the Fragment is attached to the Activity.注意: setArguments 只能在 Fragment 附加到 Activity 之前调用。 So if fragment is already attached, it will not transfer any data to the fragment.因此,如果片段已经附加,则不会向片段传输任何数据。

Bundle args = getArguments();
int value = args.getInt("some_key", 0);

you may try this,你可以试试这个

use findFragmentByTag it will help you to find fragment and send data over it.使用 findFragmentByTag 它将帮助您找到片段并通过它发送数据。

 FragmentUtama fu =(FragmentUtama)getSupportFragmentManager().findFragmentByTag(FragmentUtama.class.getSimpleName())
 Bundle bundle = new Bundle();
 bundle.putString("datak", dataj);
 fu.setArguments(bundle);

or或者

you can have one setter method in fragment and set data from activity to fragment您可以在片段中使用一个 setter 方法并将数据从活动设置为片段

from Activity.从活动。

fu.setData(dataj);

In fragment在片段中

String data;

public void setData(String data)
{
this.data=data;
}

use data using getter method of fragment使用片段的 getter 方法使用数据

public String getData()
{
return data;
}

您需要使用 Intent 的 extras 将数据传递给 MainActivity,然后在将该片段替换/添加到其容器时使用 setArguments 将其传递给属于该活动的片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM