Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • Android mode: select input not working.. How can I dynamically load images?
    import android.content.Context;
    import android.app.Activity;
    import android.content.res.AssetManager;
    //------------------------------------------------------------
    PImage[] loadImages(String folderName_){
      Activity act= this.getActivity();
      AssetManager assetManager = act.getAssets();
      PImage img_[] = null;
      try{
        String[] imgPath = assetManager.list(folderName_);
        img_ = new PImage[imgPath.length];
         for(int i=0; i<imgPath.length; i++){
         img_[i] = loadImage(folderName_ + "/" + imgPath[i]);
        }
      }
      catch(IOException ex){
           System.out.println (ex.toString());   
      }
      return img_;
    }
    
  • Why return null length in Android mode?

    YOU ARE THE BOSS!!!!

    Works perfectly!!!!!!!

    This is the final code:

    import android.content.Context;
    import android.app.Activity;
    import android.content.res.AssetManager;
    
    
    Activity act;
    String finalPath;
    ArrayList<PImage> images= new ArrayList<PImage>();
    PImage[] img;
    
    void setup(){
      size(displayWidth, displayHeight);
      //background(255);
      img = loadImages("cat");
      image(img[0], 0, 0);
    
    }
    
    void draw(){
    
    }
    
    
    PImage[] loadImages(String folderName_){
      act= this.getActivity();
      AssetManager assetManager = act.getAssets();
      try{
        String[] imgPath = assetManager.list(folderName_);
        img = new PImage[imgPath.length];
         for(int i=0; i<imgPath.length; i++){
         img[i] = loadImage(folderName_ + "/" + imgPath[i]);
        }
      }
      catch(IOException ex){
           System.out.println (ex.toString());   
      }
      return img;
    }
    

    Thank you very much, this is an excellent resource loader function, it saves me a lot of workavoiding reading files one by one.

    This function should be in the language directly available, it is very good.

  • Why return null length in Android mode?

    @erkosone=== of course your code cannot run because you transformed mine in a weird way:

    • first error is line 24 : i > must be i<....

    • second error with your PImage[]: you have to initialize it with some length (imagPath) but you initialize it only to "null"...that 's why in my code i used an arrayList().

    • third error is with your slash: you have only to give the subfolder name; doing with a slash is useless and can fire an illegal argument exception

    • below my code rewritten to integrate your method ... try it!

      import android.content.Context;
      import android.app.Activity;
      import android.content.res.AssetManager;
      
      
      PImage imga;
      Activity act;
      String finalPath;
      ArrayList<PImage> images= new ArrayList<PImage>();
      PImage[] img;
      
      void setup(){
        size(600,400);
        background(255);
        act= this.getActivity();
        img = loadImages("dossier");
        imga = img[0];
        image(imga, 0, 0);
      
      }
      
      void draw(){
      
      }
      
      
      PImage[] loadImages(String folderName_){
      
      
        AssetManager assetManager = act.getAssets();
        try{
          String[] imgPath = assetManager.list(folderName_);
          println(imgPath.length);
          img = new PImage[imgPath.length];
           for(int i=0; i<imgPath.length; i++){
           img[i] = loadImage(imgPath[i]);
          }
      
      
        }
        catch(IOException ex){
             System.out.println (ex.toString());   
        }
        println(img.length);
        return img;
      }
      
  • Why return null length in Android mode?

    DOWNLOAD EXAMPLE: https://www.dropbox.com/s/sltcqu65grhzz9q/testAssetManager.rar?dl=0

    import android.content.Context;// useless here but...
    import android.app.Activity;
    import android.os.Environment; // useless here but...
    import android.content.res.AssetManager;
    import android.graphics.Bitmap;//useless here but if you want to use android for //transforming the image when decoding from file inputstream....
    //........................................................
    PImage[] img;
    //........................................................
    void setup(){
      size(displayWidth, displayHeight);
      orientation(PORTRAIT);
      img = loadImages("cat/");
      image(img[0], 0, 0);
    }
    //........................................................
    PImage[] loadImages(String folderName_){
      Activity act;
      PImage[] img_ = null;
      act = this.getActivity();
      AssetManager assetManager = act.getAssets();
      try{
        String[] imgPath = assetManager.list(folderName_);
        println(imgPath.length);
        for(int i=0; i>imgPath.length; i++){
          img_[i] = loadImage(imgPath[i]);
        }
      }
      catch(IOException ex){
           System.out.println (ex.toString());   
      }
      return img_;
    }
    //........................................................
    
  • Why return null length in Android mode?

    @erkosone===

    code snippet below; the subfolder "dossier" is in the data folder (at the begining!) - In my case i have put only 1 image inside it; but of course you can change that && get all images with a for loop.

        import android.content.Context;// useless here but...
        import android.app.Activity;
        import android.os.Environment; // useless here but...
        import android.content.res.AssetManager;
        import android.graphics.Bitmap;//useless here but if you want to use android for //transforming the image when decoding from file inputstream....
    
        PImage imga;
        Activity act;
    
    
    
        void setup(){
    
          size(600,400);
          background(255);
          act= this.getActivity();//for fragments
          AssetManager assetManager = act.getAssets();
          try{
          String[] imgPath = assetManager.list("dossier");
          println (imgPath);
          imga = loadImage(imgPath[0]);//only 1 in the subfolder....
    
          }catch(IOException ex){
               System.out.println (ex.toString());   
           }
        image(imga, 0,0);
        };
    
  • Detect when app is put in the background

    EDIT: I think I fixed it by removing startMP=true; remove the resume void altough I'm not 100% sure since Its hard to reproduce the problem

    @kfrajer I have used your code (modifiyd) quite a few times in my app now and most of the time it works fine, but sometimes it doesn't detect for instance, when I set my phone in standby the music stops, but when I open it again it starts playing even though I haven't unlocked my phone after I unlock it it plays the music twice.

    Or sometimes when I switch between apps the music doesn't stop playing, so when I reopen the app the music starts playing twice again. I can't reproduce the problem often I feel like it happens 1 out of 30 times so maybe you noticed something I did wrong in my code. This is the code I'm using

    import android.media.MediaPlayer;
    import android.content.res.AssetFileDescriptor;
    import android.content.Context;
    import android.app.Activity;
    import android.os.Bundle;
    
    Activity act;
    Context mC;
    Context context;
    MediaPlayer snd;
    boolean startMP=true;
    AssetFileDescriptor fd;
    
    void setup()
    {
      size(800, 800);
      act = this.getActivity();
      context = act.getApplicationContext();
    }
    
    void draw()
    {
      if (startMP) {   
        startMPNow();
      }
          if(snd.isPlaying()==false) {
          try {
    
            startMPNow();
            snd.prepare();
            snd.start();
          }
          catch (IllegalArgumentException e) {
            e.printStackTrace();
          }
          catch (IllegalStateException e) {
            e.printStackTrace();
          } 
          catch (IOException e) {
            e.printStackTrace();
          }
        }
      } 
    
    void startMPNow() {
        snd= new MediaPlayer(); 
      try {
        fd = context.getAssets().openFd("music.mp3");
        snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
      }
      catch (IllegalArgumentException e) {
        e.printStackTrace();
      }
      catch (IllegalStateException e) {
        e.printStackTrace();
      } 
      catch (IOException e) {
        e.printStackTrace();
      }
      startMP=false;
    }
    
    @ Override 
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    }
    
    @ Override 
      public void onStart() {
      super.onStart();
    }
    
    @ Override 
      public void onResume() {
      super.onResume();
      startMP=true;
    }
    
    
    @ Override 
      void onPause() {
      super.onPause();
      snd.reset();
    }
    
    @ Override 
      void onStop() {
      super.onStop();
    }
    
    @ Override 
      void onDestroy() {
      super.onDestroy();
      snd.release();
      snd= null;
    }
    
    void endPlaying() {
      if (snd!=null) {
        if (snd.isPlaying()==true) {
          try {
            snd.stop();
          } 
          catch (IllegalStateException e) {
            e.printStackTrace();
          }
        }
      }
    }
    
  • Detect when app is put in the background

    Ok, so I was checking the error thrown by the application. After few changes I was getting two errors and both were of the type IllegalStateException. I check the documentation https://developer.android.com/reference/android/media/MediaPlayer.html and these error were happening, in some occasions when setting the data source (setDataSource) or when preparing (right before start)

    So I added these changes:

    A boolean field to trigger instantiation and init of the MediaPlayer. This field forces to defined the MediaPlayer and resources. This field is set onResume() and executed on draw(). This method should run only once.

    Previous field is toggle back to false after resources are set (via startMPNow() ) is executed

    Notice that in onPause(), I am resetting the MP so when I come back from either event (MENU,HOME,BACK), the MP is in the right state for setDataSource() and prepare() to operate.

    Notice there seems to be an error when the song finishes playing. I will need to look this later. For now, let's focus in returning from background.

    FINAL note: It seems accessing the HOME key via keyPressed():
    if (key==CODED && keyCode==android.view.KeyEvent.KEYCODE_HOME) {...} doesn't work at all.

    Kf

    //REFEREENCE: forum.processing.org/two/discussion/comment/100364/#Comment_100364
    //REFEREENCE: developer.android.com/reference/android/media/MediaPlayer.html#start
    //REFEREENCE: forum.processing.org/two/discussion/comment/80718/#Comment_80718
    
    
    import android.media.MediaPlayer;
    import  android.content.res.Resources;
    import android.content.res.AssetFileDescriptor;
    import android.content.res.AssetManager;
    import android.content.Context;
    import android.app.Activity;
    
    
    
    //===========================================================================
    // IMPORTS:
    
    import android.app.Activity;
    import android.content.Context;
    import android.widget.FrameLayout;
    //import android.app.Fragment;
    
    import android.os.Environment;
    import android.graphics.Color;
    import android.widget.Toast;
    import android.os.Looper;
    import android.view.WindowManager;
    import android.os.Bundle;
    import android.view.ViewParent;
    import android.view.ViewGroup;
    import android.view.View;
    import android.widget.RelativeLayout;
    import android.view.LayoutInflater;
    import android.R.string;
    
    
    //===========================================================================
    // FINAL FIELDS:
    
    
    //===========================================================================
    // GLOBAL VARIABLES:
    
    Activity act;
    Context mC;
    
    MediaPlayer snd;
    //AssetManager assets = this.getAssets();
    AssetFileDescriptor fd;
    Context context;
    Button bPlay;
    
    boolean startMP=true;
    
    void setup()
    {
      colorMode(HSB);
      size(800, 800);
      act = this.getActivity();
      context = act.getApplicationContext();
    
      //startMPNow();   <-------- FAILS, when returning from HOME/MENU button events, it seems setup is not being called at all... maybe bc the frameCount is not 1? (Guessing)
    
      bPlay = new Button(width/2, height/2, 500, color(0, 125, 255));
    }
    
    void draw()
    {
      //Next field is activated onResume() and toggle back in startMPNow() function.
      if (startMP) {   
        startMPNow();
      }
    
      background(210);
      bPlay.draw();
      textSize(30);
      textAlign(CENTER);
      fill(0, 21, 75);
      text(startMP+"\nPress for replacement\n"+snd.toString(), width/2, height/2);
    }
    
    //void keyPressed() {
    
    //  if (key==CODED && keyCode==android.view.KeyEvent.KEYCODE_HOME) {
    //    snd.reset();
    //    //endPlaying();
    //  }
    //}
    
    
    
    void mousePressed()
    {
      if (bPlay.isHovering  ()) {
    
        if (snd.isPlaying()==true) {
          try {
            snd.stop();
          } 
          catch (IllegalStateException e) {
            e.printStackTrace();
          } 
          bPlay.c = color(0, 125, 255);
        } else {
    
          bPlay.c = color(0, 125, 220);
          try {
            snd.prepare();
            snd.start();
            //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
            //snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
          }
          catch (IllegalArgumentException e) {
            e.printStackTrace();
          }
          catch (IllegalStateException e) {
            e.printStackTrace();
          } 
          catch (IOException e) {
            e.printStackTrace();
          }
          //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
        }
      }
    }
    
    void mouseReleased()
    {
      bPlay.c = color(0, 125, 255);
    }
    
    
    //  ooooooooooooooooooOOOOOOO   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    
    void startMPNow() {
    
      if (snd==null)
        snd= new MediaPlayer();
    
      try {
    
        fd = context.getAssets().openFd("Crickets.mp3");
        snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
      }
      catch (IllegalArgumentException e) {
        e.printStackTrace();
      }
      catch (IllegalStateException e) {
        e.printStackTrace();
      } 
      catch (IOException e) {
        e.printStackTrace();
      }
    
      startMP=false;
    }
    
    
    
    ////////////
    
    class Button
    {
      int x, y, w, h, r;
      color c;
    
      Button(int x, int y, int w, int h, color c) //rectangular buttons
      {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.c = c;
      }
      Button(int x, int y, int r, color c) //circular buttons
      {
        this.x = x;
        this.y = y;
        this.r = r;
        this.c = c;
      }
    
      void draw()
      {
        ellipseMode(CENTER);
        noStroke();
        fill(c);
        rect(x, y, w, h);
        ellipse(x, y, r, r);
      }
    
      boolean isHovering()
      {
        boolean result = false;
        float disX = x - mouseX;
        float disY = y - mouseY;
        if (sqrt(sq(disX) + sq(disY)) < r/2) result = true;
        return result;
      }
    }
    
    
    //===========================================================================
    // ANDROID ACTIVITY LIFECYCLE'S FUNCTIONS:
    
    
    //  @@@@@@@@@@@@
    @ Override 
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    }
    
    //  @@@@@@@@@@@@
    @ Override 
      public void onStart() {
      super.onStart();
    }
    
    //  @@@@@@@@@@@@
    @ Override 
      public void onResume() {
      super.onResume();
      startMP=true;
      //startMPNow();   <-------- FAILS, maybe mC is not available at this step
    
    }
    
    
    //  @@@@@@@@@@@@
    @ Override 
      void onPause() {
      super.onPause();
      //if (snd.isPlaying()==true) {
      //  try {
      //    snd.pause();
      //  } 
      //  catch (IllegalStateException e) {
      //    e.printStackTrace();
      //  }
      //}
      snd.reset();
    }
    
    //  @@@@@@@@@@@@
    @ Override 
      void onStop() {
      super.onStop();
      //endPlaying();
    }
    
    //  @@@@@@@@@@@@
    @ Override 
      void onDestroy() {
      super.onDestroy();
      //endPlaying();
      snd.release();
      snd= null;
    }
    
    //============================================================
    void endPlaying() {
      if (snd!=null) {
    
        if (snd.isPlaying()==true) {
          try {
            snd.stop();
          } 
          catch (IllegalStateException e) {
            e.printStackTrace();
          }
        }
    
        //snd.release();
        //snd= null;
      }
    }
    
  • Detect when app is put in the background

    @schotsl

    Here below is a version tested in P3.3.3 and AM 3.0.2

    Instructions: Tap on the screen to toggle music playing state.
    Back button will ensure music stops playing, so does HOME and MENU buttons. When you return to your application....

    • If you returned after pressing the BACK button, you can play/pause the player

    • But if you pressed HOME/MENU, then when you come back you cannot access the player. The application quits without warning, probly because of the current error handling, aka. those try-catch blocks.

    Tagging @codeanticode:

    In this scenario, when the application is returning from the background, is setup() called at all? Also, is it guaranteed that setup() is called after onResume() (I am assuming they run strictly in that order - this claim hasn't been tested)

    Kf

        //REFEREENCE: https://forum.processing.org/two/discussion/comment/100364/#Comment_100364
        //REFEREENCE: https://developer.android.com/reference/android/media/MediaPlayer.html#start()
        //REFEREENCE: https://forum.processing.org/two/discussion/comment/80718/#Comment_80718
        
        
        import android.media.MediaPlayer;
        import  android.content.res.Resources;
        import android.content.res.AssetFileDescriptor;
        import android.content.res.AssetManager;
        import android.content.Context;
        import android.app.Activity;
        
        
        
        //===========================================================================
        // IMPORTS:
        
        import android.app.Activity;
        import android.content.Context;
        import android.widget.FrameLayout;
        //import android.app.Fragment;
        
        import android.os.Environment;
        import android.graphics.Color;
        import android.widget.Toast;
        import android.os.Looper;
        import android.view.WindowManager;
        import android.os.Bundle;
        import android.view.ViewParent;
        import android.view.ViewGroup;
        import android.view.View;
        import android.widget.RelativeLayout;
        import android.view.LayoutInflater;
        import android.R.string;
        
        
        //===========================================================================
        // FINAL FIELDS:
        
        
        //===========================================================================
        // GLOBAL VARIABLES:
        
        Activity act;
        Context mC;
        
        MediaPlayer snd = new MediaPlayer();
        //AssetManager assets = this.getAssets();
        AssetFileDescriptor fd;
        Context context;
        Button bPlay;
        
        
        void setup()
        {
          colorMode(HSB);
          size(800, 800);
          act = this.getActivity();
          context = act.getApplicationContext();
          try {
        
            fd = context.getAssets().openFd("Crickets.mp3");
            snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
          }
          catch (IllegalArgumentException e) {
            e.printStackTrace();
          }
          catch (IllegalStateException e) {
            e.printStackTrace();
          } 
          catch (IOException e) {
            e.printStackTrace();
          }
        
          bPlay = new Button(width/2, height/2, 500, color(0, 125, 255));
        }
        
        void draw()
        {
          background(210);
          bPlay.draw();
          textSize(30);
          textAlign(CENTER);
          fill(0, 21, 75);
          text("Press for replacement", width/2, height/2);
        }
        
        void mousePressed()
        {
          if (bPlay.isHovering  ()) {
        
            if (snd.isPlaying()==true) {
              try {
                snd.stop();
              } 
              catch (IllegalStateException e) {
                e.printStackTrace();
              } 
              bPlay.c = color(0, 125, 255);
            } else {
        
              bPlay.c = color(0, 125, 220);
              try {
                snd.prepare();
                snd.start();
                //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
                //snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
              }
              catch (IllegalArgumentException e) {
                e.printStackTrace();
              }
              catch (IllegalStateException e) {
                e.printStackTrace();
              } 
              catch (IOException e) {
                e.printStackTrace();
              }
              //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
            }
          }
        }
        
        void mouseReleased()
        {
          bPlay.c = color(0, 125, 255);
        }
        
        
        
        ////////////
        
        class Button
        {
          int x, y, w, h, r;
          color c;
        
          Button(int x, int y, int w, int h, color c) //rectangular buttons
          {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            this.c = c;
          }
          Button(int x, int y, int r, color c) //circular buttons
          {
            this.x = x;
            this.y = y;
            this.r = r;
            this.c = c;
          }
        
          void draw()
          {
            ellipseMode(CENTER);
            noStroke();
            fill(c);
            rect(x, y, w, h);
            ellipse(x, y, r, r);
          }
        
          boolean isHovering()
          {
            boolean result = false;
            float disX = x - mouseX;
            float disY = y - mouseY;
            if (sqrt(sq(disX) + sq(disY)) < r/2) result = true;
            return result;
          }
        }
        
        
        //===========================================================================
        // ANDROID ACTIVITY LIFECYCLE'S FUNCTIONS:
        
        
        //  @@@@@@@@@@@@
        @Override 
          public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
        }
        
        //  @@@@@@@@@@@@
        @Override 
          public void onStart() {
          super.onStart();
        }
        
        //  @@@@@@@@@@@@
        @Override 
          public void onResume() {
          super.onResume();
        
          //act = this.getActivity();
          //mC= act.getApplicationContext();
        
          //try {
          //  fd = context.getAssets().openFd("Crickets.mp3");
          //  snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
          //}
          //catch (IllegalArgumentException e) {
          //  e.printStackTrace();
          //}
          //catch (IllegalStateException e) {
          //  e.printStackTrace();
          //} 
          //catch (IOException e) {
          //  e.printStackTrace();
          //}
        
        
          //if (snd.isPlaying()==false) {
          //  try {
          //    snd.prepare();
          //    snd.start();
          //    //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
          //    //snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
          //  }
          //  catch (IllegalArgumentException e) {
          //    e.printStackTrace();
          //  }
          //  catch (IllegalStateException e) {
          //    e.printStackTrace();
          //  } 
          //  catch (IOException e) {
          //    e.printStackTrace();
          //  }
          //}
          
          
        }
        
        
        //  @@@@@@@@@@@@
        @Override 
          void onPause() {
          super.onPause();
          if (snd.isPlaying()==true) {
            try {
              snd.pause();
            } 
            catch (IllegalStateException e) {
              e.printStackTrace();
            }
          }
        }
        
        //  @@@@@@@@@@@@
        @Override 
        void onStop() {
          super.onStop();
          endPlaying();
        }
        
        //  @@@@@@@@@@@@
        @Override 
        void onDestroy() {
          super.onDestroy();
          endPlaying();
        }
        
        //============================================================
        void endPlaying() {
          if (snd!=null) {
        
            if (snd.isPlaying()==true) {
              try {
                snd.stop();
              } 
              catch (IllegalStateException e) {
                e.printStackTrace();
              }
            }
        
            snd.release();
            snd= null;
          }
        }
    
  • apwidgets media player not working?

    Hi, I downloaded the apwidgets library so I can play sounds on my android phone, but it isn't quite working. I can import the library and declare a new APMediaPlayer variable, but if I so much as try to initialize it, it crashes as soon as it launches and I get this error:

    FATAL EXCEPTION: Animation Thread
    Process: processing.test.android_sound_test, PID: 5490
    java.lang.NoSuchMethodError: No virtual method getAssets()Landroid/content/res/AssetManager; in class Lprocessing/core/PApplet; or its super classes (declaration of 'processing.core.PApplet' appears in /data/app/processing.test.android_sound_test-1/base.apk)
        at apwidgets.APMediaPlayer.setMediaFile(APMediaPlayer.java:81)
        at processing.test.android_sound_test.android_sound_test.setup(android_sound_test.java:28)
        at processing.core.PApplet.handleDraw(Unknown Source)
        at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source)
        at processing.core.PApplet.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:762)
    

    Here is my code, if it helps. It's basically the example in the wiki:

    import apwidgets.*;
    APMediaPlayer player;
    
    void setup () {
      fullScreen ();
    
      player = new APMediaPlayer(this); //create new APMediaPlayer
      player.setMediaFile("Hope you have a good day.mp3"); //set the file (files are in data folder)
      player.setLooping(true); //restart playback end reached
      player.setVolume(1.0, 1.0); //Set left and right volumes. Range is from 0.0 to 1.0
      player.start(); //start play back
    }
    
    void draw () {
      background (0);
    }
    
    public void onDestroy() {
      super.onDestroy(); //call onDestroy
      if (player != null) { //must be checked because or else crash when return from landscape mode
        player.release(); //release the player
      }
    }
    
  • How to set live wallappers?

    @sarrio===

    Sorry, till now i never used the android processing mode for wallpaper; i have tried today with the example given (circles); at the end i get only an alert message saying that i have to use the selector; not time enough to understand how this lib is supposed to run

    yet i know how to set wallpaper wit android native code; here a snippet you can try (with your image)::

    //Manifest permissions set wallpaper && wallpaper hints

        import android.os.Looper;
        import android.content.Intent;
        import android.content.Context;
        import android.content.res.AssetManager;
        import android.app.WallpaperManager;
        import android.util.DisplayMetrics;
        import android.graphics.BitmapFactory;
        import android.graphics.Bitmap;
    
    
        Bitmap bitmap;
        Looper loop;
    
        void settings(){
    
          fullScreen();
        }
    
    
    
        void setup(){
         background(255,0,0); 
         orientation(PORTRAIT);
        loop.prepare();
    
          bitmap =  getBitmapFromAsset(getActivity().getApplicationContext(), "myimage.jpg");///change to your image, i think png is better
    
         if(bitmap !=null){
         setWallpaper();
        getActivity().finish();
         }
        };
    
        public void setWallpaper(){
    
        DisplayMetrics metrics = new DisplayMetrics(); 
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
            int height = metrics.heightPixels; 
            int width = metrics.widthPixels;
                    //Bitmap bitmap = BitmapFactory.decodeStream(getResources().openRawResource(R.id.image));
    
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getActivity().getApplicationContext()); 
              try {
                      wallpaperManager.setBitmap(bitmap);
    
                      wallpaperManager.suggestDesiredDimensions(width, height);
    
    
                  } catch (IOException e) {
                          e.printStackTrace();
                   }
    
        };
    
        public Bitmap getBitmapFromAsset(Context context, String filePath) {
            AssetManager assetManager = context.getAssets();
    
            InputStream istr;
            bitmap = null;
            try {
                istr = assetManager.open(filePath);
                bitmap = BitmapFactory.decodeStream(istr);
            } catch (IOException e) {
                // handle exception
            }
    
            return bitmap;
        }
    
    
    
        void draw(){
    
    
        }
    
        void mouseReleased(){///here this method is useless, yet try it perhaps with //processing wallpaper; of course if you want to use it uncomment finish() in //setup();
    
        Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
           getActivity().startActivity(intent);
        }
    
  • Using Android Studio - How to I load media files...

    Thanks Kf for taking the time to answer. I won't be able to test it for a couple of days because of other commitments but I'll give it a try.

    The dataPath and sketchFolder functions sound ideal if they work.

    I'll give it a test when I can and report back :)

    So, I haven't tested loading images yet but I can report that sketchPath returns:

    /data/user/0/com.android.test/files

    Also dataPath("test.png") returns:

    /data/user/0/com.android.test/files/data/test.png

    This is all through the android emulator.

    Now I just need to figure out how store and access the files in the correct place, more testing needed :)

    I was kind of hoping it would be as easy as creating a data folder somewhere in the android project, dropping the images/mp3s into it then using loadImage etc as you would in processing, but I can see this isn't the case.

    The getAssets function you linked to also looks like it might work but I'll have to unpick what's going on in that example, I'm still very new to android development and this is the first time I've tried Processing (I've been doing everything in p5.js).

    Cheers

    Matt

  • Using Android Studio - How to I load media files...

    This link will provide you some options as describe to Android developers:https://developer.android.com/guide/topics/data/data-storage.html

    Also in the next link check the getAssets function: https://forum.processing.org/two/discussion/comment/85705/#Comment_85705

    You can also use external storage: https://forum.processing.org/two/discussion/18126/load-image-files-from-external-storage-to-pimage/p1
    https://forum.processing.org/two/discussion/21167/accessing-sd-cards-for-storage#latest
    If you decide to go for this option, don't forget to enable sketch permission to write in the external storage.

    I am curious if dataPath("") an sketchFolder(); would work in AS. Maybe give it a try. Those functions are not documented in the reference but you can see them in action in these posts:
    https://forum.processing.org/two/discussion/11162/sketchpath-is-not-visible-3-0a9
    https://forum.processing.org/two/discussion/comment/61200/#Comment_61200
    https://forum.processing.org/two/search?Search=dataPath

    Kf

  • Trouble in android mode, using "loadImage()" & "orientation(LANDSCAPE)"?

    Hello I am new to processing. I am having trouble with processing in the android mode, using "PImage" and "loadImage" when I choose "orientation(LANDSCAPE);". My simplyfied Code:


         import java.util.*;  //To use ArrayList
        ArrayList<PImage> bilder_a;
    
        void setup() {
          fullScreen();  
          orientation(LANDSCAPE);
          background(0);  
    
          //Load Pictures:
          bilder_a=new ArrayList<PImage>(); 
          int pic_anzahl=9;
          String pic_name;
          for (int i=0; i<=pic_anzahl; i++)
          {
            pic_name="pic_a"+i+".JPG";
            bilder_a.add(loadImage(pic_name));
          }
        }
    

    I use the newest stable Version of processing, 3.3 and the newest and stable Version of SDK for Windwos 10, 64Bit. I already reinstalled the two, to see whether there is a software failure. But it does not solve anything. In my Sketch folder, I have the "data" folder with all the pictures... I am using an Oukitel K10000. My code works fine, when I run it in Java-Mode, but fails in Android-Mode:

    -post-build:

    debug: FATAL EXCEPTION: Animation Thread Process: processing.test.trouble, PID: 11536 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.app.Activity.getAssets()' on a null object reference at processing.core.PApplet.createInputRaw(Unknown Source) at processing.core.PApplet.createInput(Unknown Source) at processing.core.PApplet.loadImage(Unknown Source) at processing.test.trouble.trouble.setup(trouble.java:36) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:818) [The application does not crash, when I start it with my smartphone turned to the right landscape mode, but that is obviously not a solution...]

    The strange thing is..., the Code works fully-fine even in Android-Mode, when I delete the line "orientation(LANDSCAPE);" or when i delete the line "bilder_a.add(loadImage(pic_name));". I know, the LANDSCAPE and PImage-stuff had been discussed like a thousand times.. but I never found a discussion, that focuses, the combination of LANDSCAPE and PImage, which obviously makes me trouble.

    I hope you can help me, thanks a lot by now!

  • Has anyone managed to successfully load and display textured .OBJ models using Android Processing?

    If anyone is interested, I added a function for @codeanticode's working sample sketch above. This allows loading several .OBJ, .MTL, and texture image files using calls to loadAsset(String str, String img), where str is the .MTL and img is the texture image file (.png, .jpg, etc.) instead of writing the try/catch block for each .OBJ model. For example, I will call loadAsset("rocket.mtl","rocket.png");right before rocket = loadShape("rocket.obj");

    void loadAsset(String str, String img) {
    
      try {  
        InputStream mtlAsset = getActivity().getAssets().open(str);
        InputStream texAsset = getActivity().getAssets().open(img);
        File mtlFile = new File(getFile(str));
        File texFile = new File(getFile(img));
        copyAssetToFile(mtlAsset, mtlFile);
        copyAssetToFile(texAsset, texFile);
      } 
      catch (IOException ex) {
        throw new RuntimeException(ex);
      }
    }
    
  • Has anyone managed to successfully load and display textured .OBJ models using Android Processing?

    Hi, MTL loading in version 3.0.x of the mode is broken. The next version will include a fix, but until it becomes available you can try out this temporary workaround: copy the mtl and texture files from the assets to the location returned by sketchFile() (the mode is trying to load them from the latter, instead from the assets, which is the correct thing to do).

    The LoadDisplayOBJ built-in example could read something like this after applying the workaround:

    import java.io.FileOutputStream;
    
    PShape rocket;
    float ry;
    
    public void setup() {
      size(640, 360, P3D);
      orientation(LANDSCAPE);
    
      try {  
        InputStream mtlAsset = getActivity().getAssets().open("rocket.mtl");
        InputStream texAsset = getActivity().getAssets().open("rocket.png");
        File mtlFile = new File(getFile("rocket.mtl"));
        File texFile = new File(getFile("rocket.png"));
        copyAssetToFile(mtlAsset, mtlFile);
        copyAssetToFile(texAsset, texFile);
      } catch (IOException ex) {
        throw new RuntimeException(ex);
      }
    
      rocket = loadShape("rocket.obj");
    }
    
    public void draw() {
      background(0);
      lights();
    
      translate(width/2, height/2 + 100, -200);
      rotateZ(PI);
      rotateY(ry);
      shape(rocket);
    
      ry += 0.02;
    }
    
    String getFile(String filename) {
      File file = sketchFile(filename);    
      return file.getAbsolutePath();    
    }
    
    void copyAssetToFile(InputStream asset, File file) {
      if (!file.exists()) try {
        int size = asset.available();
        byte[] buffer = new byte[size];
        asset.read(buffer);
        asset.close();
    
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buffer);
        fos.close();
      } catch (Exception e) { 
        throw new RuntimeException(e); 
      }
    }
    

    I hope this helps.

  • Using Android MediaPlayer to play sound.

    @kfrajer, turns out using API23 got things to launch in the emulator.

    @akenaton, your code from Nov 30 works for me now.

    New question in this vein (that's why it's not in a new thread)

    How can I make this play a different sound on each press of the button? It only plays the first sound it loads (even if the fd = context.getAssets().openFd("Ni-1.mp3"); is also present in the mousePressed method ) and if I try and make it load a random sound from the data folder It either doesn't go or just sits silent.

  • Using Android MediaPlayer to play sound.

    @SnailPropulsionLabs

    I made a small mistake in my example code. Instead of keyPressed() use mousePressed(). The first function will not work on Android as you will need a keyboard.

    void mouysePressed(){
        x=mouseX;
       y=mouseY;
    }
    

    A white circle in the corner, yes, that sound about right. I believe mousePressed events will be interpreted as touch events in Android. With the above modification, every time you touch the screen on your device, the white circle will move to that touch point. I can say from what you describe about this small simple program that Android mode is working in Processing :)>-

    All my code testing has been done using API 23 and Processing 3.1.2

    Another suggestion. You are trying to get the reference to your current activity to access your files. To work around your problem, can you try accessing your file using

    dataPath("your_file_name.mp3");

    instead of

    fd = context.getAssets().openFd("some.mp3");
    snd.setDataSource(fd.getFileDescriptor()
    

    Make sure your mp3 file is inside your data folder in your current sketch folder. This is a way to work around but I am not sure it will work.

    Kf

  • Using Android MediaPlayer to play sound.

    @SnailPropulsionLabs===

    just changing some imports, some lines of code as you are in a fragment, using only 1 mp3 in order to simplify, and adding the onStop() , onPause() etc methods which are mandatory when using an instance of media player. Of course the .mp3 has to be in the data folder. The code below works, tested SonyXperiaZ3 and nexus tablet.

        import android.media.MediaPlayer;
        import  android.content.res.Resources;
        import android.content.res.AssetFileDescriptor;
        import android.content.res.AssetManager;
        import android.content.Context;
        import android.app.Activity;
    
        MediaPlayer snd = new MediaPlayer();
        //AssetManager assets = this.getAssets();
        AssetFileDescriptor fd;
        Context context;
        Button bPlay;
        Activity act;
    
        void setup()
        {
          colorMode(HSB);
          size(800, 800);
          act = this.getActivity();
          context = act.getApplicationContext();
          try {
    
            fd = context.getAssets().openFd("some.mp3");
            snd.setDataSource(fd.getFileDescriptor(),fd.getStartOffset(), fd.getLength());
          }
          catch (IllegalArgumentException e) {
            e.printStackTrace();
          }
          catch (IllegalStateException e) {
            e.printStackTrace();
          } 
          catch (IOException e) {
            e.printStackTrace();
          }
    
          bPlay = new Button(width/2, height/2, 500, color(0, 125, 255));
        }
    
        void draw()
        {
          background(210);
          bPlay.draw();
          textSize(30);
          textAlign(CENTER);
          fill(0, 21, 75);
          text("Press for replacement", width/2, height/2);
        }
    
        void mousePressed()
        {
          if (bPlay.buttonCheck()) {
            bPlay.c = color(0, 125, 220);
            try {
              snd.prepare();
              snd.start();
              //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
              //snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
    
            }
            catch (IllegalArgumentException e) {
              e.printStackTrace();
            }
            catch (IllegalStateException e) {
              e.printStackTrace();
            } 
            catch (IOException e) {
              e.printStackTrace();
            }
            //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
          }
        }
    
        void mouseReleased()
        {
          bPlay.c = color(0, 125, 255);
    
        }
    
        void onPause(){
          super.onPause();
          if(snd!=null){
    
            snd.release();
            snd= null;
          }
        }
    
        void onStop(){
          super.onStop();
          if(snd!=null){
    
            snd.release();
            snd= null;
          }
    
        }
    
    
        void onDestroy(){
           super.onDestroy();
          if(snd!=null){
    
            snd.release();
            snd= null;
          }
        }
    
    
        ////////////
    
        class Button
        {
          int x, y, w, h, r;
          color c;
    
          Button(int x, int y, int w, int h, color c) //rectangular buttons
          {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            this.c = c;
          }
          Button(int x, int y, int r, color c) //circular buttons
          {
            this.x = x;
            this.y = y;
            this.r = r;
            this.c = c;
          }
    
          void draw()
          {
            ellipseMode(CENTER);
            noStroke();
            fill(c);
            rect(x, y, w, h);
            ellipse(x, y, r, r);
          }
    
          boolean buttonCheck()
          {
            boolean result = false;
            float disX = x - mouseX;
            float disY = y - mouseY;
            if (sqrt(sq(disX) + sq(disY)) < r/2) result = true;
            return result;
          }
        }
    
  • Using Android MediaPlayer to play sound.

    All references to

    context.getAssets()...

    needs to be replaced with

    this.getActivity().getApplicationContext().getAssets()...
    

    Kf

  • Using Android MediaPlayer to play sound.

    This stopped the errors but when I compile and it is sent to the phone, it tries to launch and says "SketchName has stopped working."

    Phone tested was a Samsung Galaxy 7. Other programs work fine on the phone.

    Neither the code above or below work, they both get this error.

    I did try just having the snd.prepare(); & snd.play(); in the setup and this doesn't work either.

    main:

    import android.media.*;
    import android.content.res.*;
    import android.content.Context;
    
    MediaPlayer snd = new MediaPlayer();
    //AssetManager assets = this.getAssets();
    AssetFileDescriptor fd;
    Context context;
    Button bPlay;
    
    void setup()
    {
      colorMode(HSB);
      size(800, 800);
      try {
    
        fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
        snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
      }
      catch (IllegalArgumentException e) {
        e.printStackTrace();
      }
      catch (IllegalStateException e) {
        e.printStackTrace();
      } 
      catch (IOException e) {
        e.printStackTrace();
      }
    
      bPlay = new Button(width/2, height/2, 500, color(0, 125, 255));
    }
    
    void draw()
    {
      background(210);
      bPlay.draw();
      textSize(30);
      textAlign(CENTER);
      fill(0, 21, 75);
      text("Press for replacement", width/2, height/2);
    }
    
    void mousePressed()
    {
      if (bPlay.buttonCheck()) {
        bPlay.c = color(0, 125, 220);
        try {
          snd.prepare();
          snd.start();
          fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
          snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
    
        }
        catch (IllegalArgumentException e) {
          e.printStackTrace();
        }
        catch (IllegalStateException e) {
          e.printStackTrace();
        } 
        catch (IOException e) {
          e.printStackTrace();
        }
        //fd = context.getAssets().openFd("Ni-"+(int)random(1, 22)+".mp3");
      }
    }
    
    void mouseReleased()
    {
      bPlay.c = color(0, 125, 255);
    }
    

    Button class:

    class Button
    {
      int x, y, w, h, r;
      color c;
    
      Button(int x, int y, int w, int h, color c) //rectangular buttons
      {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.c = c;
      }
      Button(int x, int y, int r, color c) //circular buttons
      {
        this.x = x;
        this.y = y;
        this.r = r;
        this.c = c;
      }
    
      void draw()
      {
        ellipseMode(CENTER);
        noStroke();
        fill(c);
        rect(x, y, w, h);
        ellipse(x, y, r, r);
      }
    
      boolean buttonCheck()
      {
        boolean result = false;
        float disX = x - mouseX;
        float disY = y - mouseY;
        if (sqrt(sq(disX) + sq(disY)) < r/2) result = true;
        return result;
      }
    }