Android将数据从片段传递到片段

时间:2015-09-12 04:57:29

标签: android fragment

我想将数据从A片段传递给B片段。然后将B片段传递给A片段。但是当我把A传给B时,它是完美的。但是当我把B传给A时,它给了我nullpointexception。

我的代码在这里, 片段,

public static PlayRadioFragment newInstance(String url, String name, String value) {
    Bundle args = new Bundle();
    args.putString(URL, url);
    args.putString(NAME, name);
    args.putString(VALUE, value);
    PlayRadioFragment fragment = new PlayRadioFragment();
    fragment.setArguments(args);
    return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.play_radio, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
try {
        url = getArguments().getString(URL);
        if (url.length() > 0) {
            url_string = getArguments().getString(URL);
            name_string = getArguments().getString(NAME);
            image_url = getArguments().getString(VALUE);
            value = getArguments().getString(VALUE);
            name.setText(name_string);

            Log.e("url", url_string);
            Log.e("name", name_string);

            playRadio();

            image = (ImageView) getView().findViewById(R.id.imageView);
            if (image_url.length() != 0) {
                Picasso.with(getActivity()).load(image_url).fit()
                        .tag(this).into(image);
            }
        } else {
            try {
                MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
                digest.update(package_name.trim().getBytes());
                byte messageDigest[] = digest.digest();
                StringBuffer hexString = new StringBuffer();
                for (int i = 0; i < messageDigest.length; i++)
                    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
                getRadioChannelList(hexString.toString());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (NullPointerException e) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(package_name.trim().getBytes());
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            getRadioChannelList(hexString.toString());
        } catch (NoSuchAlgorithmException e2) {
            e.printStackTrace();
        } catch (JSONException e2) {
            e.printStackTrace();
        }
        e.printStackTrace();
    }


    actionPlayStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (url_string.length() > 0) {
                Intent intent = new Intent(getActivity(),
                        RadioService.class);
                if (mRadioService != null) {
                    getActivity().stopService(intent);
                    unBindMyService();
                } else {
                    playRadio();
                }
            }
        }
    });
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Intent i=new Intent(getActivity(),
                    PreferenceActivity.class);
            startActivity(i);
            break;

        case R.id.radio_list:
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(channelList,
                    new TypeToken<List<ChannelPojo>>() {
                    }.getType());
            ((MainActivity2) getActivity()).changeFragment(new MainFragment().newInstance(element.getAsJsonArray()
                    .toString(), value));
            break;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

B片段,

public static MainFragment newInstance(String url, String value) {
    Bundle args = new Bundle();
    args.putString(URL, url);
    args.putString(VALUE, value);
    MainFragment fragment = new MainFragment();
    fragment.setArguments(args);
    return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.list_main_activity, container, false);
}

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

    AdView adView = (AdView) getView().findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    value = getArguments().getString(VALUE);
    Gson gson = new Gson();
    Type type = new TypeToken<List<ChannelPojo>>() {
    }.getType();

    channelList = gson.fromJson(getArguments().getString(URL), type);
    list = (ListView) getView().findViewById(R.id.listView);
    adapter = new RadioChannelAdapter(getActivity(), channelList);
    list.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            MCrypt mcrypt = new MCrypt();
            String url = "";
            try {
                url = new String(mcrypt.decrypt(channelList.get(i).getUrl()));
                url = URLDecoder.decode(url, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ((MainActivity2) getActivity()).changeFragment(new PlayRadioFragment().newInstance(url, channelList.get(i).getName(), value));
        }
    });
}

MainActivity,

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

    changeFragment(new PlayRadioFragment());
}

public void changeFragment(Fragment f) {
    String backStateName = f.getClass().getName();
    FragmentManager manager = getSupportFragmentManager();
    boolean fragmentPopped = manager
            .popBackStackImmediate(backStateName, 0);
    if (!fragmentPopped) {
        FragmentTransaction ft = manager.beginTransaction();
        ft.replace(R.id.container, f, "Radio");
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.addToBackStack(backStateName);
        ft.commit();
    }
}

但我无法得到从B传递到A片段的问题。请帮帮我..谢谢。

2 个答案:

答案 0 :(得分:0)

我认为此行存在问题:

 changeFragment(new PlayRadioFragment()); // do not initialize fragment like this

遵循Fragment结构我认为每当你想创建一个片段实例时,请使用此代码启动它。

 MainFragment mainFragment = MainFragment.newInstance("url", "value");

感谢。

答案 1 :(得分:0)

试试这个;

  • 在每个片段中创建界面
  • 在每个界面中,使用数据
  • 在Activity类中实现两个接口。
  • 在每个重写的方法中,将值传递给每个片段。