Application context returns null when using getFilesDir ()

I do not know why this is happening. When I check DDMS, there are also no files. I am trying to access this folder in my subclass of Application. Any idea why this is happening? I need the application context to be global, so I can use it for classes that do not extend the Activity.

package mci.multipratic; import java.io.File; import java.io.FileInputStream; import java.util.Properties; import android.app.Application; import android.content.Context; public class MultiPraticApp extends Application { private static MultiPraticApp instance; public static MultiPraticAppHelper helper; public MultiPraticApp() { instance = MultiPraticApp.this; helper = new MultiPraticAppHelper(); } public static Context getContext() { return instance; } } class MultiPraticAppHelper { private int offsets = 0; private int productIndex = 0; private int recipeId = 0; private Recipe selectedRecipe; private Properties configFile; public MultiPraticAppHelper() { Context context = MultiPraticApp.getContext(); String path = context.getFilesDir() + "/config.properties"; File file = new File(path); try { FileInputStream fis = new FileInputStream(file); Properties properties = new Properties(); properties.load(fis); fis.close(); }catch(Exception ex) { ex.printStackTrace(); } } 

My manifest file:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="mci.multipratic" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="4" /> <application android:name=".MultiPraticApp" android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".EnableProductsActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> </activity> <activity android:name=".RecipeSelectionActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> </activity> <activity android:name=".ProductAdjustsActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > </activity> </application> 

+6
source share
1 answer

I believe the problem is that you are trying to initialize in the constructor. Move the code in the constructor to the OnCreate class for the application.

 @Override public void onCreate() { super.onCreate(); if(instance != null) instance = MultiPraticApp.this; if(helper != null) helper = new MultiPraticAppHelper(); } 
+6
source

Source: https://habr.com/ru/post/908071/


All Articles