简体   繁体   English

无法从片段获取上下文

[英]Unable to get context from Fragment

I am trying to call a fragment method from an activity but I am getting a null pointer exception when setting the adapter context with getActivity() in that method: 我正在尝试从活动中调用片段方法,但是在该方法中使用getActivity()设置适配器上下文时,我得到了空指针异常:

Fragment Method 片段法

public void fragmentMethod() {
            String[] names = new String[]{"name1", "name2", "name3"};
            String[] values = new String[]{value1, value2, value3};
            adapter = new MyArrayAdapter(getActivity(), names, values);
            setListAdapter(adapter);
}

Adapter 适配器

public class MyArrayAdapter extends ArrayAdapter<String> {

    private final Context context;
    private final String[] names;
    private final String[] values;

    public MyArrayAdapter (Context context, String[] names, String[] values) {
        super(context, R.layout.rowlayout, values);
        this.context = context;
        this.names = names;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
    }

}

Call to Fragment Method from Activity 从Activity调用Fragment方法

public void activityMethod() {
    FragmentName  test= new FragmentName();
    test.fragmentMethod();
}

I have tried many different things and I'm at a loss here...if I am fundamentally wrong in what I am trying to do, please let me know as I am a novice. 我尝试了许多不同的事情,但在这里我茫然不知所措...如果我在尝试做的事情上根本上是错误的,请让我知道,因为我是新手。 Thank you! 谢谢!

Edit: Stack Trace 编辑:堆栈跟踪

( Inventory is the Fragment class) Inventory是Fragment类)

This is after clicking an imageview which calls activityMethod() 这是在单击调用activityMethod()的图像视图之后

06-04 19:55:17.976    1147-1147/company.com.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
        at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
        at company.com.myapp.MyArrayAdapter.<init>(MyArrayAdapter.java:18)
        at company.com.myapp.Inventory.createList(Inventory.java:105)
        at company.com.myapp.MainActivity.newDay(MainActivity.java:177)
        at company.com.myapp.MainActivity$2.onClick(MainActivity.java:91)
        at android.view.View.performClick(View.java:4240)
        at android.view.View$PerformClick.run(View.java:17721)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

if I am fundamentally wrong in what I am trying to do, please let me know as I am a novice 如果我在尝试做的事情上根本上是错误的,请让我知道,因为我是新手

You cannot call getActivity() and get a response until the fragment is attached to an activity. 在将片段附加到活动之前,您无法调用getActivity()并获取响应。 In the case of a dynamic fragment — one you are creating directly via the constructor — this will be sometime after you commit() a FragmentTransaction that will put this fragment in a FragmentManager . 对于动态片段(您是直接通过构造函数创建的FragmentTransaction ,这将是在commit() FragmentTransaction之后的某个时间,该片段将把该片段放入FragmentManager

Moreover, there is no point in setting up your adapter until the ListView is ready. 而且,在ListView准备好之前,没有必要设置适配器。

So, simply move your fragmentMethod() code into an onViewCreated() method on your fragment. 因此,只需将fragmentMethod()代码移动到fragmentMethod() onViewCreated()方法中即可 This will be called at a point in time when both the fragment is attached to the activity and the ListView is ready to receive your adapter. 当两个片段都附加到活动并且 ListView准备好接收适配器时,将在该时间点调用此方法。

From the code above, your fragment didn't associate to any activity. 根据上面的代码,您的片段未与任何活动相关联。 So getActivity() call will return null until you attach your fragment to activity. 因此, getActivity()调用将返回null,直到您将片段附加到活动上为止。

private void activityMethod() {
    MyFragment fragment = new MyFragment();
    getSupportFragmentManager().beginTransaction()
            .add(fragment, "myfragment").commit();
    fragment.fragmentMethod();
}

onActivityCreated()onAttach()onAttach()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM