如何片段之间传递数据?片段、数据

2023-09-07 23:24:25 作者:-陌生的年华゜

对于所有那些谁是downvoting和这个问题的投票被关闭以为它是与TextView的范围.....再看看,它无关的的TextView

无法通过片段之间的数据,应用程序崩溃,我不知道我在做什么错了......我跟着这个链接 http://manishkpr.webheavens.com/android-passing-data-between-片段/

这里是code我使用 片段A(该片段传递数据)

 公共类FragmentSongs扩展片段实现Serializable,OnFragmentCreatedListener {
ListView控件SngList;


 ArrayList的< SongDetails> Songinfo = NULL;
AdapterView.AdapterContextMenuInfo信息;

@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
    捆绑savedInstanceState)
{

    ViewGroup中查看=(ViewGroup中)inflater.inflate(R.layout.fragment_song,NULL);

    SngList =(ListView控件)view.findViewById(R.id.SongList);
    registerForContextMenu(SngList);
    //文件F =新的文件(Environment.getExternalStorageDirectory()+/音乐);
    文件f =新的文件(/系统/);
    INT J = 0; INT I = 0;

    。getActivity()setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

      Songinfo = getSongsFromDirectory(F);



    //下面的排序完成
    如果(Songinfo.size()大于0)
    {

        为(J = 0; J< Songinfo.size(); J ++)
        {
            对于(I = J + 1; I< Songinfo.size();我++)
            {
                SongDetails一个= Songinfo.get(ⅰ);
                SongDetails B = Songinfo.get(J);
                如果(a.getSong()与toLowerCase()的compareTo(b.getSong()与toLowerCase())≤; 0)
                {

                    Songinfo.set(I,B);
                    Songinfo.set(J,A);
                }
            }

        }






   SngList.setAdapter(新CustomAdapter(Songinfo));
   返回查看;
    }
    否则返回NULL;

}
OnFragmentCreatedListener监听;
@覆盖
公共无效onAttach(活动活动){
    super.onAttach(活动);
    尝试 {
        听者=(OnFragmentCreatedListener)getActivity();
        listener.onFragmentCreated(Songinfo);
    }赶上(ClassCastException异常E){
        抛出新ClassCastException异常(activity.toString()+必须实现onFragmentCreated);
    }
}
 

片段B(接收器片段)

 公共类FragmentArtists扩展片段{
    ArrayList的< SongDetails> songinfo2;
的ViewGroup图。
int类型= 5; // TextView的文字;
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
        捆绑savedInstanceState)
{上下文的背景下;
LayoutInflater LF = getActivity()getLayoutInflater()。

    鉴于=(ViewGroup中)inflater.inflate(R.layout.fragment_artist,NULL);
//视图= lf.inflate(R.layout.test,集装箱,假);
//视图= inflater.inflate(R.layout.test,集装箱,假);


 S = S + 5;
//文字=(TextView的)view.findViewById(R.id.tt);当我用这个,它工作正常,但我想这样做的另一种方法

//text.setText("makzzz");when我用这个,它工作正常,但我想这样做的另一种方法
返回查看;

}

 无效setSongList(ArrayList中< SongDetails> songinfo)
{// TextView的文字=(TextView的)this.getView()findViewById(R.id.tt); //当我用这个观点是不是全球
      TextView的文字=(TextView的)view.findViewById(R.id.tt); //当我用这个,认为是全球性的;
      // TextView的文字=(TextView的)view.findViewById(R.id.tt);
    //文字=(TextView的)super.getView()findViewById(R.id.tt)。


     text.setText(makzzz);
 

在支架活动的方法(本次活动拥有片段)

 保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.mymusic);


           碎片=新矢量<片断>();
            fragments.add(Fragment.instantiate(此,FragmentSongs.class.getName()));
            fragments.add(Fragment.instantiate(此,FragmentArtists.class.getName()));
            fragments.add(Fragment.instantiate(此,FragmentPlaylists.class.getName()));
            fragments.add(Fragment.instantiate(此,FragmentAlbums.class.getName()));


            ViewPagerAdapter适配器=新ViewPagerAdapter(super.getSupportFragmentManager(),片段);


            ViewPager寻呼机=(ViewPager)super.findViewById(R.id.viewpager);



            pager.setAdapter(适配器);
            pager.setOffscreenPageLimit(4);

            pager.setCurrentItem(0);

    }公共无效onFragmentCreated(ArrayList中< SongDetails> MSG){
            FragmentArtists的OBJ =(FragmentArtists)fragments.get(1);
            Obj.setSongList(MSG);
            }

    }
 
如何实现食品饮料实验室的全面数字化转型

回调类:

 包源$ C ​​$ c.jazzplayer;

进口的java.util.ArrayList;

公共接口OnFragmentCreatedListener {
    公共无效onFragmentCreated(ArrayList中< SongDetails> MSG);

}
 

这里是logcat的

  09-19 23:50:46.851:E / AndroidRuntime(2125):显示java.lang.NullPointerException
09-19 23:50:46.851:E / AndroidRuntime(2125):在源头code.jazzplayer.FragmentArtists.setSongList(FragmentArtists.java:55)
09-19 23:50:46.851:E / AndroidRuntime(2125):在源头code.jazzplayer.MyMusic.onFragmentCreated(MyMusic.java:45)
09-19 23:50:46.851:E / AndroidRuntime(2125):在源头code.jazzplayer.FragmentSongs.onAttach(FragmentSongs.java:128)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:883)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:823)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:819)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.view.ViewPager.populate(ViewPager.java:1066)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.view.ViewPager.populate(ViewPager.java:914)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.View.measure(View.java:12603)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.View.measure(View.java:12603)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.View.measure(View.java:12603)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
09-19 23:50:46.851:E / AndroidRuntime(2125):在com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2072)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.View.measure(View.java:12603)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1044)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.os.Handler.dispatchMessage(Handler.java:99)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.os.Looper.loop(Looper.java:137)
09-19 23:50:46.851:E / AndroidRuntime(2125):在android.app.ActivityThread.main(ActivityThread.java:4340)
09-19 23:50:46.851:E / AndroidRuntime(2125):在java.lang.reflect.Method.invokeNative(本机方法)
09-19 23:50:46.851:E / AndroidRuntime(2125):在java.lang.reflect.Method.invoke(Method.java:511)
09-19 23:50:46.851:E / AndroidRuntime(2125):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
09-19 23:50:46.851:E / AndroidRuntime(2125):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-19 23:50:46.851:E / AndroidRuntime(2125):在dalvik.system.NativeStart.main(本机方法)
 

错误的是在这条线的code

TextView的文字=(TextView的)view.findViewById(R.id.tt); //此行是在接收片段(fragmentArtist)

解决方案

正如我已经在我的评论说,你想用片段来上班时,它不是正常初始化呢。当 FragmentSongs 连接到活动(由 ViewPager 它会出现),其 onAttach()方法被调用。在这种方法中,你投了活动到您的收听,但是你也立即拨打了听者的回调。这将使您的应用程序崩溃(跟你贴的除外),因为在监听你想与第二片段的 ViewPager FragmentArtists 。这片段尚未初始化,在这一刻的第一个片段的 ViewPager 几乎没有被连接到活动而你已经试图与这显然会失败的第二个片段的视图工作。

您链接到本教程是好的,简单的,但确定(没有去那个链接我以为你的code是从教程)。问题是,你使用的code,从一个非常简单的场景更复杂的情况下(事实上,如果你插入你现在的code该教程中的code,你会得到相同的异常(调用听众太早))。

这是回调监听器接口应采用,而片段完全建立(如当用户使用的应用程序,并选择一首歌曲,要显示他的应用程序的艺术家部分(在那一刻拨打监听器和使得它传递数据))还精心处理的片段不被使用的可能性。

如果你需要传递这么早在片段的生命周期,你不能保证该片段片段之间的数据尚未公布(像你这样做与调用听者 onAttach()),然后执行该片段从活动中获取数据的直接时,它的建成,在其生命周期的方法之一。什么你传递,目前还不清楚,所以我可以说这里没有太多。

For all those who are downvoting and voting for this question to be closed thinking it has something to do with the scope of textview.....then have a look,it has nothing to do with the scope of textview

Unable to pass data between fragments,the app crashes,i don't know what i am doing wrong...i followed this link http://manishkpr.webheavens.com/android-passing-data-between-fragments/

here is the code i am using Fragment A(this fragment is passing the data)

public class FragmentSongs extends  Fragment implements Serializable,OnFragmentCreatedListener {
ListView SngList;


 ArrayList<SongDetails> Songinfo=null;
AdapterView.AdapterContextMenuInfo info;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) 
{

    ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_song, null);

    SngList = (ListView) view.findViewById(R.id.SongList);
    registerForContextMenu(SngList);
    //File f=new File(Environment.getExternalStorageDirectory()+"/Music");
    File f=new File("/system/");
    int j=0;int i=0;

    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

      Songinfo = getSongsFromDirectory(f);



    //sorting done below
    if (Songinfo.size()>0)
    {

        for( j=0; j<Songinfo.size();j++)
        {
            for ( i=j+1 ; i<Songinfo.size(); i++)
            { 
                SongDetails a=Songinfo.get(i);
                SongDetails b=Songinfo.get(j);
                if(a.getSong().toLowerCase().compareTo(b.getSong().toLowerCase())<0)
                {   

                    Songinfo.set(i,b );
                    Songinfo.set(j,a);
                }
            }

        }






   SngList.setAdapter(new CustomAdapter(Songinfo));
   return view;
    }
    else return null;

}
OnFragmentCreatedListener listener;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        listener = (OnFragmentCreatedListener) getActivity();
        listener.onFragmentCreated(Songinfo);
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement onFragmentCreated");
    }
}

fragment B(the receiver fragment )

    public class FragmentArtists extends Fragment {
    ArrayList<SongDetails> songinfo2;
ViewGroup view;
int s=5;//TextView text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
{Context context;
LayoutInflater lf = getActivity().getLayoutInflater();   

    view = (ViewGroup) inflater.inflate(R.layout.fragment_artist,  null);
// view =  lf.inflate(R.layout.test,container, false);
// view = inflater.inflate(R.layout.test,container, false);


 s=s+5;
//     text=(TextView)view.findViewById(R.id.tt);when i use this,it works fine but i want to do it in the other method

//text.setText("makzzz");when i use this,it works fine but i want to do it in the other method
return view;

}

 void setSongList(ArrayList<SongDetails> songinfo) 
{    //TextView text=(TextView)this.getView().findViewById(R.id.tt);//when i used this view was not global
      TextView text=(TextView)view.findViewById(R.id.tt);//when i used this,view was global;
      //TextView text=(TextView)view.findViewById(R.id.tt);
    // text=(TextView)super.getView().findViewById(R.id.tt);


     text.setText("makzzz");

the method in holder activity (this activity holds the fragments)

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mymusic);


           fragments = new Vector<Fragment>();
            fragments.add(Fragment.instantiate(this, FragmentSongs.class.getName()));
            fragments.add(Fragment.instantiate(this, FragmentArtists.class.getName()));
            fragments.add(Fragment.instantiate(this, FragmentPlaylists.class.getName()));
            fragments.add(Fragment.instantiate(this, FragmentAlbums.class.getName())); 


            ViewPagerAdapter adapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);


            ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);



            pager.setAdapter(adapter);
            pager.setOffscreenPageLimit(4);

            pager.setCurrentItem(0);

    }      public void onFragmentCreated(ArrayList<SongDetails> msg) {
            FragmentArtists Obj=(FragmentArtists)  fragments.get(1);
            Obj.setSongList(msg);
            }

    }

the callback class:

package sourcecode.jazzplayer;

import java.util.ArrayList;

public interface OnFragmentCreatedListener {
    public void onFragmentCreated(ArrayList<SongDetails> msg);

}

here is the logcat

  09-19 23:50:46.851: E/AndroidRuntime(2125): java.lang.NullPointerException
09-19 23:50:46.851: E/AndroidRuntime(2125):     at sourcecode.jazzplayer.FragmentArtists.setSongList(FragmentArtists.java:55)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at sourcecode.jazzplayer.MyMusic.onFragmentCreated(MyMusic.java:45)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at sourcecode.jazzplayer.FragmentSongs.onAttach(FragmentSongs.java:128)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:883)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:823)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:819)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1066)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.View.measure(View.java:12603)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.View.measure(View.java:12603)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.View.measure(View.java:12603)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2072)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.View.measure(View.java:12603)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1044)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.os.Looper.loop(Looper.java:137)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at android.app.ActivityThread.main(ActivityThread.java:4340)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-19 23:50:46.851: E/AndroidRuntime(2125):     at dalvik.system.NativeStart.main(Native Method)

the error is in this line of code

TextView text=(TextView)view.findViewById(R.id.tt); //this line is in the receiver fragment (fragmentArtist)

解决方案

As I already said in my comment you're trying to work with a Fragment when it's not properly initialized yet. When the FragmentSongs is attached to the Activity(action requested by the ViewPager where it will appear) its onAttach() method is called. In this method you cast the Activity to your listener, but you also call immediately the listener's callback. This will make your app crash(with the exception you posted) because in that listener you're trying to work with the view of the second Fragment of the ViewPager, FragmentArtists. This Fragment isn't yet initialized, at this moment the first fragment of the ViewPager is barely being attached to the activity and you're already trying to work with the view of the second fragment which will obviously fail.

The tutorial you linked to is ok, simplistic, but ok(without going to that link I assumed your code is from the tutorial). The problem is that you used that code from a very simplistic scenario in a more complex situation(in fact if you insert your current code in that tutorial's code you'll get the same exception(calling the listener too early)).

That callback listener interface should be used while the fragment is fully built(like when the user is using the app and selects a song and you want to show to him the artist part of the app(at that moment call the listener and make it pass data)) also carefully handling the possibility of a fragment not being available.

If you need to pass data between fragments so early in the fragment's lifecycle that you can't guarantee the fragment is yet available(like you do with calling the listener in onAttach() of a fragment) then implement the fragment to get the data directly from the activity when it's built, in one of its lifecycle methods. What you're passing it's not clear so there isn't much I can say here.