How to get data directory path in Android?

UPDATED: 06 June 2013
What is data directory in Android?
Android generates private directory on Internal Memory for each application installed on device. Its not accessible using any explorer until the device is rooted. This private directory allocated to store important files for your application. Path of private directory is like /data/data/com.example.application.

Source Code (ContextBean.java)
ContextBean used to access application context in any class.
import android.content.Context;
/*
 * This will help you to use application context in any file with in project.
 */
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
   return localContext;
  }
  public static void setLocalContext(Context localContext) {
   ContextBean.localContext = localContext;
  }
}

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {
...
ContextBean.setLocalContext(getApplicationContext());
...
}

Source Code (CommonUtil.java)
Now create CommonUtil.java (change class name as you wish). That will return the Data Directory path in String. This code also has the code to get the Application path on External Storage.
import android.os.Environment;
import android.util.Log;
public class CommonUtil {
  public String getDataDir() {
              try {
     return ContextBean.getLocalContext().getPackageManager().getPackageInfo(
      ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
       } catch (Exception e) {
     Log.w("Your Tag", "Data Directory error:", e);
     return null;
              }
  }
  // read more about Environment class : http://developer.android.com/reference/android/os/Environment.html
  public String getDownloadFolder() {
    return ContextBean.getLocalContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
   .toString();
  }
}

getDownloadFolder() method gives you the path /Android/data/package_name/files/Downloads. You can change the path as per your requirement like...
  • DIRECTORY_ALARMS
  • DIRECTORY_DCIM
  • DIRECTORY_DOWNLOADS
  • DIRECTORY_MOVIES
  • DIRECTORY_MUSIC
  • DIRECTORY_NOTIFICATIONS
  • DIRECTORY_PICTURES
  • DIRECTORY_PODCASTS
  • DIRECTORY_RINGTONES

Source Code
CommonUtil objCommonUtil = new CommonUtil();
String path_to_data = objCommonUtil.getDataDir();

For further enhancement read developers guide: http://developer.android.com/guide/topics/data/data-storage.html

0 comments :