Android:将数据(额外)传递给片段 [英] Android: Pass data(extras) to a fragment

查看:16
本文介绍了Android:将数据(额外)传递给片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 编程新手,在将 Parcelable 的 ArrayList 传递给片段时遇到问题.这是启动的 Activity(运行良好!),其中 feedlist 是一个可分割的 Music 的 ArrayList.

I'm new to Android programming and I'm having problems while passing an ArrayList of a Parcelable to a fragment. This is the Activity that is launched(working well!) where feedlist is an ArrayList of a parcelable Music.

Intent in = new Intent(context, ListMusicsActivity.class);

in.putExtra("arrayMusic", feedList);
activity.startActivity(in);

片段Activity的onCreate()方法:

The fragment Activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitymusiclist);

    if(savedInstanceState != null)
    {
        ListMusicFragment frag = new ListMusicFragment();
        frag.setArguments(getIntent().getExtras());
    }
}

片段代码:

public class ListMusicFragment extends SherlockFragment{

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState)
{
    listMusics = (ArrayList<Music>) getArguments().getSerializable("arrayMusic");
    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

我认为问题出在这一行

listMusics = (ArrayList<Music>) getArguments().getSerializable("arrayMusic");

最后这是我的音乐课:

public class Music implements Parcelable{

private String url;
private String artist;
private String title;
private String duration;
private String info_url;
private String lyrics;


public Music(String url, String artist, String title, 
    String duration, String lyrics, String info_url)
{
    this.url = url;
    this.artist = artist;
    this.title = title;
    this.duration = duration;
    this.lyrics = lyrics;
    this.info_url = info_url;
}

public Music(Parcel in)
{
    url = ParcelUtils.readString(in);
    artist = ParcelUtils.readString(in);
    title = ParcelUtils.readString(in);
    duration = ParcelUtils.readString(in);
    info_url = ParcelUtils.readString(in);
    lyrics = ParcelUtils.readString(in);
}

public String getUrl()
{
    return url;
}

public String getArtist()
{
    return artist;
}

public String getTitle()
{
    return title;
}

public String getDuration()
{
    return duration;
}

public String getLyrics()
{
    return lyrics;
}

public String getInfo()
{
    return info_url;
}

@Override
public int describeContents() {
    return 0;
}


@Override
public void writeToParcel(Parcel dest, int flags)
{
    ParcelUtils.writeString(dest, url);
    ParcelUtils.writeString(dest, artist);
    ParcelUtils.writeString(dest, title);
    ParcelUtils.writeString(dest, duration);
    ParcelUtils.writeString(dest, lyrics);
    ParcelUtils.writeString(dest, info_url);
}

public static final Parcelable.Creator<Music> CREATOR = 
    new Parcelable.Creator<Music>() {

    public Music createFromParcel(Parcel in)
    {
        return new Music(in);
    }

    public Music[] newArray(int size)
    {
        return new Music[size];
    }
};
}

当我运行此代码时,我遇到的问题是 Fragment onCreateView() 方法中的 java.lang.NullPointerException.如果有人指出我正确的方向以了解我失败的地方,我将不胜感激.

When I run this code the problem I get is a java.lang.NullPointerException in the Fragment onCreateView() method. I would appreciate a lot if someone pointed me in the right direction to see where I am failing.

编辑:问题已解决:我只需要将此行添加到片段 Activity onCreate() 方法中(否则 getArguments() 将返回 null):

EDIT: Problem solved: I just needed to add this line to the fragment Activity onCreate() method(othwewise the getArguments() would return null):

getSupportFragmentManager().beginTransaction()
    .add(android.R.id.content, frag).commit();

并将其添加到片段代码中:

And add this to the fragment code:

@Override
    public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);

    Bundle bundle = getArguments();
    if(bundle != null)
    {
        listMusics = bundle.getParcelableArrayList("arrayMusic");
        listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));
    }
}

其中,listMusics 是 Parcelable 音乐的 ArrayList.

where, listMusics is an ArrayList of Parcelable Music.

推荐答案

两件事.首先,我认为您没有正确添加要传递给片段的数据.您需要传递给片段的是一个包,而不是一个意图.例如,如果我想将 int 值发送到片段,我将创建一个包,将 int 放入该包中,然后将该包设置为要使用的参数创建片段时.

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

第二次检索您需要获取发送到片段的参数的信息.然后根据您用来标识它的键提取该值.例如在您的片段中:

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

你得到的东西取决于你放的东西.此外,默认值通常为 null 但并非必须如此.这取决于您是否为该参数设置了默认值.

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

最后,我认为你不能在 onCreateView 中做到这一点.我认为您必须在片段的 onActivityCreated 方法中检索此数据.我的推理如下.onActivityCreated 在底层 Activity 完成其自己的 onCreate 方法后运行.如果您在活动的 onCreate 方法期间将要检索的信息放置在包中,则在片段的 onCreateView 期间它不会存在.尝试在 onActivityCreated 中使用它,稍后更新您的 ListView 内容.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

这篇关于Android:将数据(额外)传递给片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆