从Android的FragmentActivity参数传递给片段 [英] Passing parameters from Android FragmentActivity to Fragment

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

问题描述

当我试着从FragmentActivity一个参数传递给一个片断它给了我在getArguments空指针异常()中的片段。

下面是我的FragmentActivity code

 公共类IndexChartActivity扩展FragmentActivity {
        @覆盖
        公共无效的onCreate(包savedInstanceState){
            super.onCreate(savedInstanceState);

            的setContentView(R.layout.index_chart);

            IndexFragmentActivity indexFragment =
 (IndexFragmentActivity)getSupportFragmentManager()findFragmentById(R.id.index_fragment)。
            indexFragment.newInstance(ASPI);

        }

    }
 

下面是index_chart.xml

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:后台=#FFFFFF
    机器人:方向=垂直>

    <片段
        机器人:ID =@ + ID / header_fragment
        机器人:名称=com.lk.ignitionit.cse.util.HeaderFragmentActivity
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/>

    <片段
        机器人:ID =@ + ID / index_fragment
        机器人:名称=com.lk.ignitionit.cse.util.IndexFragmentActivity
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/>

    <片段
        机器人:名称=com.lk.ignitionit.cse.util.ChartFragmentActivity
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/>

< / LinearLayout中>
 

和这里是片段

 公共类IndexFragmentActivity扩展片段{
    保护ImageView的ivASPI;
    保护ImageView的ivMPI;
    保护ImageView的IVSP;
    受保护的TextView tvMain;
    受保护的TextView tvTop;
    受保护的TextView tvBottom;
    串响应=无效;
    字符串结果= NULL;
    的String [] resultArr = NULL;
    叠B =新包();
    字符串INDEXTYPE = NULL;
    INT布局;
    IndexFragmentActivity F = NULL;

    公共IndexFragmentActivity的newInstance(字符串索引){
        F =新IndexFragmentActivity();
        捆绑的args =新包();
        args.putString(索引类型,索引);
        f.setArguments(参数);
        返回F;
    }

    公共字符串getSelectedIndex(){
        返回f.getArguments()的getString(索引类型)。
    }
    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
        如果(getSelectedIndex()。等于(ASPI)){
            布局= R.layout.aspi_header;
        }否则,如果(getSelectedIndex()。等于(MPI)){
            布局= R.layout.mpi_header;
        }其他{
            布局= R.layout.sp_header;
        }
        查看查看= inflater.inflate(布局,集装箱,假);

        tvMain =(TextView中)view.findViewById(R.id.tv_main);
        tvTop =(TextView中)view.findViewById(R.id.tv_top);
        tvBottom =(TextView中)view.findViewById(R.id.tv_bottom);


        新ServiceAccess()执行();

        tvMain.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                b.putString(类型,S&安培,P SL20);
                活性活性= getActivity();
                意向意图=新的意图(活动,IndexChartActivity.class);
                intent.putExtras(B);
                startActivity(意向);

            }
        });

        返回查看;
    }
}
 

和这里是我的错误。

 产生的原因:显示java.lang.NullPointerException
在com.lk.ignitionit.cse.util.IndexFragmentActivity.getSelectedIndex(IndexFragmentActivity.java:69)
 

我提到很多有关这个计算器的问题,并试图给出的样本code http://developer.android.com/guide/components/fragments.html 为好。但仍没有运气

真的AP preciate任何反馈这个,因为这似乎是我不能想出一个很基本的问题。

在此先感谢

解决方案
  1. 摆脱活动的从不从活动继承所有类的名称。例如, IndexFragmentActivity 不是活动

  2. 的onCreate()您的实际活动,您所呼叫的 findFragmentById()来检索片段,然后调用的newInstance()在该片段。然而,该片段将不存在在第一时间的onCreate()被调用时,你会失败,这里有一个 NullPointerException异常 。请正确地处理这种情况。

  3. 方法名的newInstance Java中最常使用的工厂模式,其中的newInstance()到位的公共构造方法来使用静态方法创建一些类的实例。你的的newInstance()方法不是静态。这将导致混乱对于那些谁来找你保持code。

  4. 您拨打的newInstance()的onCreate(),创建新的片段实例,然后把它扔掉,这是浪费时间。

因此​​,假设你的片段的原始实例(无论它来自)没有一个参数捆绑设置,这可以解释你的 NullPointerException异常 getSelectedIndex()

  

当我试着从FragmentActivity一个参数传递给一个片段

要传递参数给的新建的片段,使用静态 的newInstance()方法和参数捆绑创建的的片段是完全合理的。

要传递一个参数已存在的片段,只需调用在该片段一些setter方法​​。

When Im trying to pass a parameter from FragmentActivity to a Fragment it gives me null pointer exception in the getArguments() in the Fragment.

Here is my FragmentActivity Code

  public class IndexChartActivity extends FragmentActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.index_chart);

            IndexFragmentActivity indexFragment =   
 (IndexFragmentActivity)getSupportFragmentManager().findFragmentById(R.id.index_fragment);
            indexFragment.newInstance("ASPI");

        }

    }

Here is the index_chart.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/header_fragment"
        android:name="com.lk.ignitionit.cse.util.HeaderFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment
        android:id="@+id/index_fragment"
        android:name="com.lk.ignitionit.cse.util.IndexFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment
        android:name="com.lk.ignitionit.cse.util.ChartFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

and Here is the Fragment

public class IndexFragmentActivity extends Fragment {
    protected ImageView ivASPI;
    protected ImageView ivMPI;
    protected ImageView ivSP;
    protected TextView tvMain;
    protected TextView tvTop;
    protected TextView tvBottom;
    String response = null;
    String result = null;
    String []  resultArr = null;
    Bundle b = new Bundle();
    String indexType = null;
    int layout;
    IndexFragmentActivity f = null;

    public  IndexFragmentActivity newInstance(String index) {
        f = new IndexFragmentActivity();
        Bundle args = new Bundle();
        args.putString("indextype", index);
        f.setArguments(args);
        return f;
    }

    public String getSelectedIndex() {
        return f.getArguments().getString("indextype");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(getSelectedIndex().equals("ASPI")){
            layout = R.layout.aspi_header;
        }else if(getSelectedIndex().equals("MPI")){
            layout = R.layout.mpi_header;
        }else{
            layout = R.layout.sp_header;
        }
        View view = inflater.inflate(layout, container, false);

        tvMain = (TextView) view.findViewById(R.id.tv_main);
        tvTop = (TextView) view.findViewById(R.id.tv_top);
        tvBottom = (TextView) view.findViewById(R.id.tv_bottom);


        new ServiceAccess().execute("");

        tvMain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                b.putString("type", "S&P SL20");
                Activity activity = getActivity();
                Intent intent = new Intent(activity, IndexChartActivity.class);
                intent.putExtras(b);
                startActivity(intent);  

            }
        });

        return view;
    }
}

and Here is my ERROR

Caused by: java.lang.NullPointerException
at com.lk.ignitionit.cse.util.IndexFragmentActivity.getSelectedIndex(IndexFragmentActivity.java:69)

I referred lots of stackoverflow questions relevant to this and tried the sample code given http://developer.android.com/guide/components/fragments.html as well. But still no luck

Really appreciate any feed back on this as this seems to be a very basic issue which I cannot figure out..

Thanks in Advance

解决方案

  1. Get rid of Activity from the names of all classes that do not inherit from Activity. For example, IndexFragmentActivity is not an Activity.

  2. In onCreate() of your actual activity, you are calling findFragmentById() to retrieve a fragment, then calling newInstance() on that fragment. However, the fragment will not exist the first time onCreate() is called, and you will fail here with a NullPointerException. Please correctly handle this case.

  3. The method name newInstance in Java is most commonly associated with the factory pattern, where newInstance() is a static method used in place of a public constructor to create instances of some class. Your newInstance() method is not static. This will cause confusion for those who come after you to maintain the code.

  4. You call newInstance() in onCreate(), create the new fragment instance, and then throw it away, which is a waste of time.

Hence, assuming that your original instance of your fragment (wherever it came from) does not have an arguments Bundle set, that would explain your NullPointerException in getSelectedIndex().

When Im trying to pass a parameter from FragmentActivity to a Fragment

To pass a parameter to a newly created fragment, using a static newInstance() method and the arguments Bundle to create the new fragment is perfectly reasonable.

To pass a parameter to a fragment that already exists, simply call some setter method on that fragment.

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

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