No serial library Processing for smartphone. Help

Whilst its potentially not possible in android you can download turbo editor on the app store and this will allow you to create your desired file.

As you can see you can set the name and folder of the file.

furthermore here is a sketch I posted a few days back which allows you to do exactly this.

you should be able to use the first sketch posted.

just set the following line in setup

my full updated code in case that last link is problematic.

Summary
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;
import android.content.DialogInterface;
import android.graphics.Color;
import android.widget.TextView;
import android.view.Gravity;
import processing.core.PApplet;
import android.app.Activity;
import android.app.AlertDialog;

fileOutput f;

String s2 = "oifoifnowibf";
void settings() {
  size(600, 600, P2D);
};

public void setup() {

  f = new fileOutput(this);
  f.setLocation("notes/test.txt");
  f.setAndroidDialogue("No","Yessss");
};

public void draw() {
  background(255);
  if (f.fileContent!=null) {
    fill(0);
    text(f.counter, 20, 10);
    text(f.fileContent, 20, 20);
  } else {
    fill(0);
    text("no file", 20, 20);
  }
};

void mousePressed() {
  if (f.writeFile) {
    f.writeLn(s2+hour()+":"+minute()+":"+second());
    f.close();
    f.loadStrings();
  }
  if(!f.writeFile)f.dialogBox();
};
Summary

class fileOutput {
public PApplet applet;
public FileWriter output;
float x, y, w, h;
public boolean save, onMouseUp, mdown, debug, append = true, appendFile, match,
append2, overWrite = true, overWriteOnce = true, writeOnce, writeFile, click,
getPermission = true, fileExists, reWrite;
public int counter=-1, counter2;
public File file, file2, file3;
public File SDcards ;
public String location, filePath, folderPath = “”;
String text = “oioijsofoivnsoindv”, absolutePath, ext, fileName, fileContent = “”;
String androidDialogueTitle = “Would you like to overWrite”,
dialogueB1Title = “”,dialogueB2Title = “”,dialogueBody;
Permission p;
Activity activity;
Context context;
TextView msg;
int msgId;

fileOutput() {
};

fileOutput(boolean a, PApplet applet) {

this.applet = applet;
p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
overWrite = true;
appendFile = true;

};

fileOutput(PApplet app) {
applet = app;
p = new Permission(applet, “WRITE_EXTERNAL_STORAGE”);
//init();
};
//currently unused
fileOutput(String location, PApplet applet) {

this.applet = applet;
p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
setLocation(location);
init();

};

fileOutput(PApplet applet, String location) {

this.applet = applet;
p = new Permission(applet, "WRITE_EXTERNAL_STORAGE");
setLocation(location);
init();

};

void getAndroidInfo() {
activity = applet.getActivity();
context = activity.getApplicationContext();
absolutePath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
};

void init() {
x = 0;
y = 0;
w = applet.width;
h = applet.height;

String s1 = "Would you like to overWrite "+fileName+"."+ext+"?";
float dboxWidth = 120;
float tSize = 20;
applet.textSize(tSize);
float dw = applet.textWidth(s1)+100;
float dboxHeight = 150;
float dx = applet.width/2-dw/2;
float dy = applet.height/2-50/2;

};

void loadStrings() {
loadFile(context);
};

String loadFile(Context context) {

FileInputStream fis = null;
if (writeFile) {
  try {
    if (!reWrite)fis = new FileInputStream (new File(file2.getAbsolutePath()));
    else fis = new FileInputStream (new File(file3.getAbsolutePath()));
    
    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
    fileContent = sb.toString();

    fis.close();
  }
  catch (Exception e) {
    println("cannot fetch file", e);
  } 
  finally {
    if (fis != null) {

      fis = null;
    }
  }
}
return fileContent;

};

void open() {
};

void close() {
try {
output.flush();
output.close();
}
catch(IOException e) {
}
};

void write(String s) {

if (!overWrite)checkLocation();
try {

  output = new FileWriter(file2, append);
}
catch(IOException e) {
}
printWrite(s);

};

void writeLn(String s) {
if (!overWrite)checkLocation();
try {
output = new FileWriter(file2, append);
}
catch(IOException e) {
}
printWriteLn(s);
};

void write(String s) {
if (!overWrite)checkLocation();
try {
output = new FileWriter(file2, append);
}
catch(IOException e) {
}
printWrite(s);
};

void writeLn(String s) {
if (!overWrite)checkLocation();
try {
output = new FileWriter(file2, append);
}
catch(IOException e) {
}
printWriteLn(s);
};

void printWrite(String s) {
if (!overWrite)checkLocation();
try {
output.append(s);
}
catch(IOException e) {
}
};

void printWriteLn(String s) {
if (!overWrite)checkLocation();
try {
output.append(s);
output.append(“\n”);
}
catch(IOException e) {
}
};

void printWrite(String s) {
if (!overWrite)checkLocation();
try {
for (int i=0; i<s.length; i++) {
output.append(s[i]);
}
}
catch(IOException e) {
}
};

void printWriteLn(String s) {
if (!overWrite)checkLocation();
try {
for (int i=0; i<s.length; i++) {
output.append(s[i]);
output.append(“\n”);
}
}
catch(IOException e) {
}
};

void checkLocation() {
boolean k = false;
String s1 = “Would you like to overWrite “+fileName+counter+”.”+ext+“?”;
try {
//
file = new File(absolutePath, folderPath);
if (!file.exists()&&counter==-1) {
file.mkdirs();
file2 = new File(file, “/”+fileName+“.”+ext);
androidDialogueTitle = file.getAbsolutePath();
PApplet.println(“checking file1”, file2);
if (file2.exists()) {
counter ++;

      PApplet.println("File Exists");
      //dbox.main.title.label = s1;
    }
  } else if (counter==-1) {
    fileExists = true;
    counter = 0;
    k = true;
  } else k = true;
  if (overWrite&&writeOnce) {
    k=false;
  } else if (overWrite&&!writeOnce&&writeFile) {
    writeOnce = true;
    k = true;
  }
  boolean k1 = false;
  if (writeFile)
    while (k&&counter<100&&!k1) {
      s1 = fileName+counter+"."+ext+"?";
      try { 

        file2 = new File(absolutePath+"/"+folderPath+"/"+fileName+counter+"."+ext);
        file3 = new File(absolutePath+"/"+folderPath+"/"+fileName+(counter)+"."+ext);
        androidDialogueTitle = file3.getAbsolutePath();
        if (file2.exists()) { 
          counter++;
        } else {
          PApplet.println("checking file2", file2);
          //output = new FileWriter(file2, append);
          k = false;
          k1 = true;
          break;
        }
      } 
      catch (Exception e) { 
        PApplet.println("Error while saving file: " + e);
      }
    }
  if (k1||!writeFile) {
    //PApplet.println("file",file);
    //PApplet.println("Fname",folderName);
    //PApplet.println("fileName",fileName);
    //PApplet.println("counter",counter);
    //PApplet.println("ext",ext);
    if (file2==null&&counter<0)file2 = new File(file+"/"+fileName+"."+ext); 
    else if (file2==null)file2 = new File(file+"/"+fileName+"."+ext); 
    if (output==null) {
      //img.save(file+"/"+fileName+counter+"."+ext);

      if (writeFile)output = new FileWriter(file2, append);
      PApplet.println("File saved successfully.");
      //use write or append
    }
  }
  if (reWrite) {
    file2 = new File(file+"/"+fileName+counter+"."+ext); 
    output = new FileWriter(file2, append);
  }
  println("write file", folderPath, fileName, counter, ext);
  if (reWrite)overWrite = true;
} 
catch (IOException e) {
  e.printStackTrace();
}

};

void listen() {
//if(writeFile&&dbox.main.getButton(0).click)checkLocation();
};

void setLocation(String s) {
if (getPermission)getAndroidInfo();
location = s;
folderPath = s.substring(0, s.lastIndexOf(“/”));
fileName = s.replace(folderPath+“/”, “”);
getExt(fileName);
PApplet.println(“Fname”, folderPath);
PApplet.println(“fileName”, fileName);
PApplet.println(“counter”, counter);
PApplet.println(“ext”, ext);
checkLocation();
init();
}

void getExt(String location) {

int count = 0;
fileName = location.substring(0, location.indexOf("."));
ext = location.replace(fileName, "");
ext = ext.replace(".", "");
ext = ext.replace(fileName, "");

};

void dialogBox() {

msg = new TextView(activity); 
msg.setBackgroundColor(Color.BLUE);
msg.setTextSize(32);
msg.setText(dialogueBody); 
msg.setGravity(Gravity.CENTER_HORIZONTAL); 
msg.setTextColor(Color.WHITE); 

activity.runOnUiThread(new Runnable() {
  public void run() {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setView(msg);
    
    androidDialogueTitle += " "+fileName+"."+ext+"?";
    builder.setTitle(androidDialogueTitle);
    builder.setPositiveButton(dialogueB1Title, 
      new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, 
        int which) {
          writeFile = true;
          overWrite = false;
          reWrite = true;
          
      }
    }
    );
    builder.setNegativeButton(dialogueB2Title, 
      new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, 
        int which) {
          writeFile = true;
          overWrite = true;
        //act.finish();
      }
    }
    )
    .show();
  }
}
);

};

void setAndroidDialogue(String s1,String s2){
dialogueB1Title = s1;
dialogueB2Title = s2;

};

void setAndroidDialogue(String s1,String s2,String s3){
androidDialogueTitle = s1;
dialogueB1Title = s2;
dialogueB2Title = s3;

};

void setAndroidDialogueTitle(String s1){
androidDialogueTitle = s1;
};

void setDialogueColor(){

};

public boolean click() {
boolean k = false;
if (pos()&&applet.mousePressed&&!click) {
click = true;
k = false;
} else if (click&&!applet.mousePressed) {
k = true;
click = false;
}
return k;
};

public boolean pos(PVector mouse) {
return mouse.x>x&&mouse.x<x+w&&mouse.y>y&&mouse.y<y+h;
};

public boolean pos() {
return applet.mouseX>x&&applet.mouseX<x+w&&applet.mouseY>y&&applet.mouseY<y+h;
};
};

Permissions

Summary
public class Permission{
  
  PApplet parent;
  String p;

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

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

};
f.setLocation("xml/test.xml");

1 Like

20210513_101644
my experience with the filesystem is above average. there is no problem anywhere to find, create, change, change the properties of a file or directories. I was doing system administration twenty years ago and now I use a powerful two-pane file manager that allows you to work with the system in the same way as in DOS and WINDOWS, and maybe even better.

https://www.ghisler.com/efaqgeneral.htm

So have you managed to create the required file?

1 Like

only up to today’s recommendations.
I have not checked the current offers yet.
at work, little free time.

if you make changes to the native manifest file in APDE 5.2, then whenever I run APDE5.2, it overwrites all my changes and restores the original file state.

I will try to shoot a video and give access. if you see everything is fine then write, and if not, then also write what is wrong.

I created a new manifest file from your post.
Replaced original auto generated APDE5.2, but when I ran APDE5.2 everything came back.

UPDATE! 2021-05-17 I now have this working:
APDE USB / OTG communication - #24 by glv

This post below is now deprecated:


Adding to the topic…

I took these steps:

  1. I purchased an OTG cable to add to my tool chest.

  2. I got this working using Android Mode on PC.
    No serial library Processing for smartphone. Help - #149 by glv
    I used the device_filter.xml for this.
    This worked so I proceeded to explore further…

  3. UPDATE! I can’t reproduce this on APDE so back to the drawing board!

  4. I found this issue in step #3:
    Impossible to grant access to USB port through AndroidManifest · Issue #84 · Calsign/APDE · GitHub
    The template for the AndroidManifest.xml is here:
    APDE/AppManifest.xml.tmpl at master · Calsign/APDE · GitHub
    The template was copied, renamed, modified and put in the root of my sketch.

  5. There is an APDE v 0.5.2 pre-release that I did not try:
    Releases · Calsign/APDE · GitHub
    There was a discussion about this version in #4 above.

Some interesting posts in this topic for further exploration… one day but not anytime soon.

:)

1 Like

I am trying to understand your wonderful post.
1.It’s impossible without using a computer
2. You have tried APDE5.1 but it fails and you want to try later on APDE5.2. But you don’t have time now.
2021_05_12_11_09_30

May be i found a way to change any manifest. but there is no way to load device_filter.xml file
20210513_024358

Why do you need device xml?

1 Like

I dont know.
what was advised, then I do.

Honestly not sure about specifics as i have not coded for arduino.

None of my android projects have required me to change any activity.xml or other file.

However this may be a requirement for usb.

In any case i wish you all the best. Im not sure what else i can add to this, as you should now be able to write any file to your device and set any permission, anything else will be outside the scope of my understanding and would require further research.

In any case you’re welcome to dig through the aandroid reference.

Good luck

2 Likes

not all files and not all permission. it is an android system, there are many restrictions.
you helped me a lot and I will have a few questions, because your direction turned out to be the most difficult and I need time to figure it out.

Whilst true, for the scope of this sketch you shouldnt need any extreme permissions or obscure folders. The code above will write files to internal storage and allow you to set all basic permissions, again for the scope of this project this should be fine.

1 Like

I apologize to everyone present, if I cannot answer immediately, with a delay, and also do not immediately try the code, this is not disrespect towards those present. I am constantly on the road or at work, I answer immediately when there is an opportunity. And to try the code, I need even more time, I am an electrical engineer, not a professional programmer. This topic and the solution to this issue are very important to me. I am very grateful to everyone who helps and participates in finding a solution.
thank_you

1 Like

No problem. Its difficult to be able to troubleshoot everything with so many different types of devices out there and the forum whilst ideal for gathering a great number of people still fails in some instances as the nuances of communication arent very well translated.

In any case a bit of patience with forum members goes a long way.

furthermore processing android is something which i too have been frustrated with. The documentation is often obscure and requires a certain level of understanding, and unfortunately it feels very much like the community gave up on it.

Rapid development on android could be a thing if we spend some time converting or wrapping some of the android native code into more userfriendly code.

I am currently working on this my BMS, which was initially named for Button Menus and Sliders, but can also mean Button management System (a little observational humour for you). This library will do just that.

im currently converting the last code i sent you so others in the future may have a simpler time with this.

Features i will add.

Full custom ui with;

Sliders
Menus
Tabs
SliderBoxes
Dock
Dropdownmenu
Textinput
File browser
File save
File Read
Image save
Image load
Bluetooth
Camera
Serial

I shall also add android specific code whereever possible so you can make use of:

Toast notifications
Android text input
Android lists
Etc.

It is a work in progress and currently only the ui part is useable but i still have to wrestle with some unexpected button behaviour and need to complete the styling option to reflect modern alternatives.

Should be done with logic and ui functionality and read write and text input this week.

The rest will have to wait, as like you this is really a hobby which i do along my main job, and so cannot dedicate all my time.

Also please take a look at some of the following

@noel is no longer on the forum but left a great resource in these repos.

And of course the ketai repo with other examples

http://ketai.org/examples/

Unfortunately neither of these have serial, but with a bit of time i feel we should be able to provide a satisfactory solution.

1 Like

20210513_203843

@ZENAR57

i think the main issue is how to initialization the serial library

read this link and back to the library then compare the steps

https://hingxyu.medium.com/arduino-android-serial-communication-b72b124142fb

for instance this step has to be approved in similar way with serial library

b) Add jitpack to your project.build.gradle file.

and this step also but i do not know how to add it

Add library to dependencies

dependencies {
implementation ‘com.github.mik3y:usb-serial-for-android:3.3.1’
}

1 Like

as for this device_filter.xml
you can create the path in side your project folder if the path not already presented and add it with any editor

in one of my photos up i show where is the path

you have to be sure that you followed this steps

1. Add library to your project:

Add jitpack.io repository to your root build.gradle:

allprojects { repositories { … maven { url ‘https://jitpack.io’ } } }

Add library to dependencies

dependencies { implementation ‘com.github.mik3y:usb-serial-for-android:3.3.1’ }

2. If the app should be notified when a device is attached, add device_filter.xml to your project’s res/xml/ directory and configure in your AndroidManifest.xml .

<activity android:name="…" …>

1 Like