質問

I am currently writing a Class to export some data to CSV using a AsyncTask. I have written the class however when I call its constructor and pass in the context to be set I get a null pointer exception on the Context in the class. My CSV writer class is below:

public class ExportCSVTask extends AsyncTask<String, Void, Boolean> {

        Context mContext;

        public ExportCSVTask(Context context){
            Log.e("Error in MainActivity","Inside the Constructor");
            mContext = context;
        } 

        private final ProgressDialog dialog = new ProgressDialog(mContext);

I have debugged the application and found that it does hit the "ExportCSVTask" with the correct context being passed, however it doesn't do anything any skips passed it. I created a Log message to test this and it appears that nothing inside the constructor is being executed and I don't know why. I have also put the code below which is what initiates the constructor:

try
                {
                    ExportCSVTask task = new ExportCSVTask(getApplicationContext());
                    task.execute("");
                }
                catch(Exception ex)
                {
                    Log.e("Error in MainActivity",ex.toString());
                }

I would really appreciate some help on this as I am stumped as to what could be causing the issue.

役に立ちましたか?

解決

I believe the issue is where you have this statement:

private final ProgressDialog dialog = new ProgressDialog(mContext);

That is a class level variable and the assignment runs before the constructor does. Hence at that point, mContext is null.

Just declare it without an assignment:

private final ProgressDialog dialog;

...and set it inside the constructor (after setting mContext):

dialog = new ProgressDialog(mContext);

他のヒント

Member variables are initialized first and the constructor is called only then. So you dialog is initialized while mContext is still in its default null value.

Move the dialog initialization to constructor, or better yet, onPreExecute().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top