Null at the time the context is invoked within the method...

Asked 1 years ago, Updated 1 years ago, 114 views

First, the flow is

OnAttach() saves the received context in the global variable mContext, which is not null until then.

Invoke public static void refreshSpinner(), where public void setSpinner(ArrayListal) is called

Called public void setSpinner (ArrayListal). Check mContext here to make it null.

MyActivity.java

/*  MyActivity.java  */

private Context mContext;

    @Override
    public void onAttach(Context ctx){
        super.onAttach(ctx);
        mContext = ctx;
       //mContext and ctx are not null
    }

public static void refreshSpinner(){
    File[] f = new File ("path...").listFiles();
    ArrayList l = new ArrayList();
    for(File a : f){
        l.add(a.getAbsolutePath());
    }
    new MyActivity().setSpinner(l);
}

public void setSpinner(ArrayList al){
   //MContext is null when checked here
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, al);
            spinner.setAdapter(adapter);
            spinner.setSelection(0);
}

What's going on here?

Obviously, what wasn't null is null only in the method...

android android-context null

2022-09-22 17:59

1 Answers

There are a few things you need to know.

The static method does not pass this as the first parameter.

You will know that you can access the instance variable in the form of this.variable. If the reason why it is possible is the instance method, this is always automatically passed as the first parameter. I just don't feel it because it's implied. However, this is not delivered to the static method.

onAttach is the callback method. This means that the creation of objects would have been within the Android framework.

The problem is that the static method refreshSpinner is explicitly creating objects with newMyActivity().setSpinner(l);. This object is not an object with onAttach invoked.

In summary, onAttach is null because it was not called because a new object was created.

Get context by looking at the link below.

https://developer.android.com/reference/android/view/View.html#getContext%28%29


2022-09-22 17:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.