Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

android - Transfer data from Fragment Activity to Fragment

I'm working with a bluetooth service in my application which ables me to get received message from another device. In my FragmentActivity, i'm using a handler to get this message:

FragmentActivity:

  public final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                  //my code

                  case MESSAGE_READ:
                         byte[] readBuf = (byte[]) msg.obj;
                         byte[] alpha = null;
                         alpha=readBuf;

                         if(alpha!=null){
                          //my code..
              }
        }
  }

From this Handler I would like to get a data and transfer it to a Fragment. I tried to use bundle but it doesn't work..

The code I tried:

In FragmentActivity:

    Intent intent = new Intent();
intent.setClass(getApplicationContext(), General.class);
Bundle bundle=new Bundle();
bundle.putInt("battery", bat);
intent.putExtra("android.intent.extra.INTENT", bundle);

In Fragment:

Bundle bundle = getActivity().getIntent().getExtras();
if (bundle != null) {
int mLabel = bundle.getInt("battery", 0);
Toast.makeText(getActivity(), "tottiti: "+mLabel, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "prout", Toast.LENGTH_SHORT).show();
}

The application is returning "prout" which means that it can't get my data from my FragmentActivity.

Is there any other way to get a data frome a fragmentActivity and transfer it to a fragment?

Thank you for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you need pass the data to the fragment at creation time, you could use setArguments() to pass data to the fragment, and getArguments() to read that data.

Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();

Then in onCreate() method of the fragment:

Bundle bundle=getArguments(); 
int mLabel = bundle.getInt("battery", 0);

But if the fragment is already created, then you could create a method inside the fragment that you'll use to pass data, something like this:

fragment.setBattery(bat);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...