Android Cannot get access to data folder

My devices are Samsung also. Phone S4, and Tablet E 9.6
But both have normal access to the sketch folder. There must be something wrong with your phone. Can’t you try it on another phone?

1 Like

After you get storage permission, you can use following method to get root path.

    public static String getRootFilesDirPath() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File[] files = ContextCompat.getExternalFilesDirs(getContext().getApplicationContext(),null);
            return files[0].getAbsolutePath();
        } else {
            return getContext().getFilesDir().getAbsolutePath();
        }
    }
2 Likes
Initializing build sequence…
Deleted old build folder
Injected log broadcaster
Detected architecture armeabi-v7a

Packaging resources with AAPT…
Compiling with ECJ…
----------
1. ERROR in /data/user/0/com.calsignlabs.apde/app_build/src/processing/test/save_picture/Save_Picture.java (at line 25)
	File[] files = ContextCompat.getExternalFilesDirs(getContext().getApplicationContext(),null); 
	               ^^^^^^^^^^^^^
ContextCompat cannot be resolved
----------
2. ERROR in /data/user/0/com.calsignlabs.apde/app_build/src/processing/test/save_picture/Save_Picture.java (at line 25)
	File[] files = ContextCompat.getExternalFilesDirs(getContext().getApplicationContext(),null); 
	                                                  ^^^^^^^^^^
Cannot make a static reference to the non-static method getContext() from the type PApplet
----------
3. ERROR in /data/user/0/com.calsignlabs.apde/app_build/src/processing/test/save_picture/Save_Picture.java (at line 29)
	return getContext().getFilesDir().getAbsolutePath(); 
	       ^^^^^^^^^^
Cannot make a static reference to the non-static method getContext() from the type PApplet
----------
3 problems (3 errors)
Compiling with ECJ failed

Well it works on bluestacks but i need my computer for that. Also i dont have another phone. Well now i know my phone sucks. Atleast its not me. Thank you for all your work i really appreciate it now i just gotta fix this thing… somehow

@PhoenixStormJr , @noel ===
the code given by @noel must run on your phone and the error you can get with it is only if you dont get the WRITE_EXTERNAL_STORAGE permission; as it seems to me that @noel is using lollipop he does not ask for permissions on runtime but if your phone is using more than lollipop YOU HAVE TO ASK for this permission on runtime & by code, asking only with the Manifest will not work…

1 Like

@akenaton Lollipop also requires this permission. The app APDE, (entirely based on Processing for Android) has an extra feature. It can run in a “preview” mode. Preview mode skips several steps of the build process: DX-Merge , APKBuilder, ZipSigner, and installation. The only significant remaining steps are AAPT, ECJ , and DX-Dex, so the build process is much more streamlined. The preview mode also gives automatic permissions. But when you want to export, using the “app” mode, permissions are required. On a Galaxy S9+, the entire process to run code, takes less than two seconds. Codeanticode was talking about implementing it in PC android as well. APDE is a free open source project from calsign and I really would ike to see them together on one Github. I was never able to run Processing for Android in emulator mode. And running on device directly with a usb cable, takes minutes every time. You could give it a try☺.

@noel ====

Lollipop also requires this permission

yes but NOT in runtime && by code…

@technew
Isn’t ContextCompat a part of support library v4? How did you add support library 4 into your processing project?

1 Like

@PhoenixStormJr
We don’t give up easily. Let’s do a test the other way around. With the link below you can download a small app that saves and loads images into a folder on your phone (with the same code). It is a zoomable Mandelbrot image generator. If it doesn’t run you maybe have to reset your phone.
This way you’ll also help me to verify if my methods for text and other views, automatic resizing on different screen resolutions, work properly. I would also appreciate testing by others.
The link for the apk pure here and zipped here.

The app looks this way on my phone.

2 Likes

I use processing as a library in Android studio. Processing IDE is supposed to handle support library automatically but I’m not really sure.

Now i know its my phone

I really apappreciate all your help and i will fix my phone when I have time

1 Like

I did find a work around. The only reason I needed it was for saving but now when I click the <> button and select apk i can save ONLY to the root of the folder… I just needed to save files… thanks for helping

1 Like

Does the app I linked above run?

No but i can save now… just only to 1 folder

paulgoux solved it! One year and seven months later I FINALLY got the answer! (I replied in case anyone else was struggling with this topic)

AndroidManifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="">
    <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="28"/>
    <application android:icon="@mipmap/ic_launcher" android:label="">
        <activity android:name=".MainActivity" android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;

Activity activity; 
Context context; 
Permission p;
String s1 ,s2 = "iuiugifuy";
String absolutePath;
public boolean overWrite = true;

public void setup(){
  size(600,600);
  p = new Permission(this,"WRITE_EXTERNAL_STORAGE");
  activity = this.getActivity(); 
  context = activity.getApplicationContext();
  absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
  
};

public void draw(){
  background(255);
  
  
  if(s1!=null){
    fill(0);
    text(s1,20,20);
  }else{
    fill(0);
    text("no file",20,20);
  }
  
};

void mousePressed(){
  generateNoteOnSD(context,"test.txt",s2+hour()+":"+minute()+":"+second());
  readFromFile(context);
};


public void generateNoteOnSD(Context context, String FileName, String text) {
  try {
    //
      File root = new File(absolutePath, "Notes");
      if (!root.exists()) {
          root.mkdirs();
      }
      File gpxfile = new File(root, FileName);
      //set to false will overwrite the file, set to true to append
      FileWriter writer = new FileWriter(gpxfile,false);
      //use write or append
      writer.append(text);
      // use \n to add new line
      writer.append("\n");
      
      writer.flush();
      writer.close();
      println("write file");
  } catch (IOException e) {
      e.printStackTrace();
  }
};

  
private String readFromFile(Context context) {

    FileInputStream fis = null;
    try {

        fis = new FileInputStream (new File(absolutePath+"/notes/"+"test.txt"));
        InputStreamReader isr = new InputStreamReader(fis);
        // READ STRING OF UNKNOWN LENGTH
        StringBuilder sb = new StringBuilder();
        char[] inputBuffer = new char[2048];
        int l;
        // FILL BUFFER WITH DATA
        while ((l = isr.read(inputBuffer)) != -1) {
            sb.append(inputBuffer, 0, l);
            println("write data",inputBuffer, 0, l);
        }
        // CONVERT BYTES TO STRING
        s1 = sb.toString();
        
        fis.close();

    }catch (Exception e) {
      println("cannot fetch file",e);
    } finally {
        if (fis != null) {
            
            fis = null;
        }
    }
import android.os.Environment;
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Build.VERSION_CODES; 
import processing.core.PConstants;
import android.app.Activity; 

PImage img;
Activity activity; 
boolean image_saved;
boolean permissions_granted;

// Folowing file name is the folder you save your image file in.
// If it does not exist it will be created automatically
String folder_name = "MyImageFolder";

// Folowing string is the name of your image file
// Be sure to include extension.
String image_file = "MyImage.jpg";
Permission wstorage,rstorage;
void setup() {
  wstorage = new Permission(this,"WRITE_EXTERNAL_STORAGE");
  rstorage = new Permission(this,"READ_EXTERNAL_STORAGE");
  size(displayWidth, displayHeight);
  background(0, 0, 200); 
  rectMode(CENTER);
  rect(width/2, height/2, width, height/2);
  textAlign(CENTER);
  String str = "Click to save an image.";
  textSize(12);
  float twf = width/textWidth(str);
  textSize(8*twf);
  fill(0);
  text(str, width/2, height/2);
  img = get();
  //img.save(
};

void draw() {
  if (image_saved) {
    background(0, 0, 200);
    fill(255);
    text("Image saved.", width/2, height/2);
  } 
};

void mousePressed() {
  saveMyImage(folder_name, image_file);
};

void saveMyImage(String sf, String tf) { 
  try { 
    String absolute_path = new String(Environment.getExternalStorageDirectory().getAbsolutePath()); 
    File file = new File(absolute_path+"/"+sf); 
    //println(file);
    if (!file.exists()) { 
      boolean success = true; 
      success = file.mkdirs();
      if(success){
        save(file+"/"+tf);
        image_saved = true;
        println("File saved successfully.");
        println("Path",absolute_path,"File",file);
      }
      else {
        println("no File");
        println("Path",absolute_path,"File",file);
      }
    } 
    
    
  } 
  catch (Exception e) { 
    //println("Error while saving file: " + e);
  }
};
public class Permission{
  
  String permissionName;
  PApplet parent;

  public Permission(PApplet pParent,String permissionName) {
    parent = pParent;
    this.permissionName = permissionName;
    parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
  };

  public void onPermissionResult(boolean granted) {
    if (!granted) {
      PApplet.println("User did not grant camera permission. "+ permissionName +" is disabled.");
    }
  };

};

I had the permissions enabled but I didn’t have the manifest file in my sketch folder! That’s why it didn’t work! Also a simpler solution is save.save(dataPath(“square.png”));

2 Likes