Botellita Taponzito
Botellita Taponzito

Reputation: 121

How can I get the true path where my file is?

I want to know if a file exists. I have created it and stored with sharedPreferences, but Android doesn´t get me the true route.

public class SplashScreen extends AppCompatActivity
{
   super.onCreate(SavedInstanceState);
   setContentView(R.layout.activity_splash_screen);
   String FILE_NAME = "configAjustes.xml";

   new Handler().postDelayed(() -> {
      File file1 = new File(getApplicationContext().getFilesDir().getPath(),FILE_NAME);
      Log.d("fc","file1 is "+file1);
      Log.d("fc","file1 name is "+file1.getName);

      if(file1.exists())
      {
         Log.d("fc","exists");
         Intent inMain = new Intent (getApplicationContext(),MainActivity.class);
         startActivity(inMain);
         finish();
      }else
      {
         Log.d("fc","not exists");
         Intent inSettings= new Intent(getApplicationContext(),Settings.class);
         startActivity(inSettings);
         finish();
      }
   },2000);
}

I get the following: screen output

the problem is that the path that android gives me is not true, because the xml file is not in "files". It is in "shared_prefs" true path of file

How can I get the true path where my file is?

Upvotes: 0

Views: 63

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006944

Normally, we do not think of SharedPreferences as a file, and there is no direct and reliable way to access them as a file.

The closest solution is:

File prefsDir = new File(getApplicationInfo().dataDir,"shared_prefs"); 
File file1 = new File(prefsDir, FILE_NAME);

Or possibly:

File dataDir = getFilesDir().getParentFile();
File prefsDir = new File(dataDir,"shared_prefs"); 
File file1 = new File(prefsDir, FILE_NAME);

However, there is no guarantee that these will work across all Android OS versions and all devices.

Upvotes: 2

Related Questions