Reputation: 155
I am trying to get my app's root directory, but getting the following exception. I even defined my context. How do I fix this? I have been stuck on this since the past 3 hours.
ContextWrapper c = new ContextWrapper(this);
String FileDirectory = c.getFilesDir().getPath();
exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
edit:
public class MainActivity extends AppCompatActivity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
ContextWrapper c = new ContextWrapper(this);
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String FileDirectory = c.getFilesDir().getPath();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Upvotes: 0
Views: 5758
Reputation: 93561
You can't make those calls at creation time. The context is not valid until after super.onCreate() has been called. Move all of that code into onCreate and it should be ok. Although making a ContextWrapper is kind of a waste- an Activity is a Context, just call getFilesDir directly on this.
Upvotes: 2