Get Texture from Unity in Android - java

Good morning.
I want to use the Android plug-in to save the image to Internal Storage and import the image from Internal Storage.
When you save an image in Unity, the user can access the saved image.
I do not want users to access stored images.
So I tried to create and use Android plugin, but it is not working properly.
I need help.
Android Native Code :
public void WriteToInternalStorage(String name, byte[] data) {
try{
FileOutputStream fileOutputStream = context.openFileOutput(name, context.MODE_PRIVATE);
fileOutputStream.write(data);
fileOutputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public byte[] ReadToInternalStorage(String name) {
StringBuffer stringBuffer = new StringBuffer("");
byte[] buffer = new byte[1024];
int n;
try {
FileInputStream fileInputStream = context.openFileInput(name);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(stringBuffer).getBytes();
}
Unity Code :
public void NativeCall_ReadInternalStorage(string name)
{
byte[] test = instance.Call<byte[]>("ReadToInternalStorage", name);
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(test);
Thumbnail.texture = tex;
}
The image is not displayed properly.
I do not know what's wrong with the Android native code.
Please help me.

Related

How to store audio input in an array from recorder?

I have been working on a project that implements pattern recognition on breathing patterns as a form of communication for speech impaired speakers.
I have an idea of how to do it, but I have a very basic knowledge of Java. I am stuck. I wanted to get the audio data from microphone and store it in an array. In doing so, I can then pass the data and normalise it, extract features from it, and then store the new array in my database.
Please help. Thank you!
First you Should Encode To String
private void encodeAudio(String selectedPath) {
byte[] audioBytes;
try {
// Just to check file size.. Its is correct i-e; Not Zero
File audioFile = new File(selectedPath);
long fileSize = audioFile.length();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(selectedPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
audioBytes = baos.toByteArray();
// Here goes the Base64 string
_audioBase64 = Base64.encodeToString(audioBytes, Base64.DEFAULT);
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
}
Then Decode it in Received Device
private void decodeAudio(
String base64AudioData,
File fileName,
String path,
MediaPlayer mp) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(Base64.decode(base64AudioData.getBytes(), Base64.DEFAULT));
fos.close();
try {
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.start();
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Cannot read data from file

I am trying to read values from CSV file which is present in package com.example.
But when i run code with the following syntax:
DataModel model = new FileDataModel(new File("Dataset.csv"));
It says:
java.io.FileNotFoundException:Dataset.csv
I have also tried using:
DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));
Still not working.
Any help would be helpful.
Thanks.
If this is the FileDataModel from org.apache.mahout.cf.taste.impl.model.file then it can't take an input stream and needs just a file. The problem is you can't assume the file is available to you that easily (see answer to this question).
It might be better to read the contents of the file and save it to a temp file, then pass that temp file to FileDataModel.
InputStream initStream = getClass().getClasLoader().getResourceAsStream("Dataset.csv");
//simplistic approach is to put all the contents of the file stream into memory at once
// but it would be smarter to buffer and do it in chunks
byte[] buffer = new byte[initStream.available()];
initStream.read(buffer);
//now save the file contents in memory to a temporary file on the disk
//choose your own temporary location - this one is typical for linux
String tempFilePath = "/tmp/Dataset.csv";
File tempFile = new File(tempFilePath);
OutputStream outStream = new FileOutputStream(tempFile);
outStream.write(buffer);
DataModel model = new FileDataModel(new File(tempFilePath));
...
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
public void run() {
String csvFile = "file path of csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// Do stuff here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
CSV file which is present in package com.example
You can use getResource() or getResourceAsStream() to access the resource from within the package. For example
InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader
(note exception handling and file closing are omitted above for brevity)

Filenotfoundexception on newer versions of android API Level 4 and later

I am working on a project with google maps where i try to retrieve bitmaps from URL and save it to internal memory.After downloading the bitmap into internal memory i try to read it from memory using the following code:
public Bitmap getImageBitmap(Context context, String name) {
FileInputStream fis = null;
try {
File myFile = new File (path_file + File.separator + name);
fis = new FileInputStream(myFile);
Bitmap b = BitmapFactory.decodeStream(fis);
return b;
} catch(Exception e) {
return null;
} finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The problem is that the code works fine on Android 2.6 , but it throws Filenotfoundexception at this line
fis = new FileInputStream(myFile);
Why does the code work fine on older versions of android but throws exception on newer versions of android?How do i fix the issue?
EDIT:
The issue was with the code which downloads the bitmap:
The code that i am using is:
public void downloadfile(String path,String filepath)
{
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
The code throws NetworkonMainThreadException at this line: InputStream is = ucon.getInputStream();
This error is thrown only on the newer android version.Please help!!
Try this..
Just use
path_file=MainActivity.this.getFilesDir();
EDIT
class downloadfile extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... urls) {
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
}
}
Instead if calling downloadfile method use below
new downloadfile().execute();
You are trying to perform a network related operation in Main thread,you are getting this NetworkonMainThreadException.
Refer to my answer here for more explanation.
In your case try downloading the bitmap file in worker thread. You can use an Asynctask for it and download bitmap in doInBackground().
Refer this example

Retrieving bitmap from internal memory fails on newer android versions

I am developing an android project with google maps and it has custom images for the markers of google map.But instead of downloading the images each time, the first time the marker images are downloaded into internal memory, from the second time onwards i check if the images are downloaded and then they are retrieved from memory.
But the code works fine on my phone (Android version 2.6.3) , But when i tried on newer devices (Android 4 and above) the code for retrieving the downloaded bitmap image returns null.
The code for checking if the images have been downloaded:
public void checkcategoryimagesavailable() {
path_file=MainActivity.this.getFilesDir().getAbsolutePath();
for(int i=0;i<catprearr.size();i++) {
File file = new File(path_file+File.separator+catprearr.get(i)+".png");
if(file.exists()) {
} else {
downloadfile(URL_image+catprearr.get(i)+".png",path_file+File.separator+catprearr.get(i)+".png");
}
}
setvaluesonmap();
}
The code for downloading the images:
public void downloadfile(String path,String filepath) {
try {
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
} catch(Exception e) {
e.printStackTrace();
}
}
The code for setting the markers:
public void setvaluesonmap() {
for(int i=0;i<list.size();i++) {
final Store_data s=list.get(i);
Bitmap obj=getImageBitmap(MainActivity.this,s.category+".png");
obj=Bitmap.createScaledBitmap(obj,68,62,false);
iv_category_logo.setImageBitmap(obj);
googleMap.addMarker(new MarkerOptions().title(s.store_name)
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(MainActivity.this, custom_layout)))
.position(new LatLng(Double.parseDouble(s.store_latitude),Double.parseDouble(s.store_longitude))));
}
}
The code for retrieving the downloaded image:This is the troubled code:the bitmap returns null on newer devices
public Bitmap getImageBitmap(Context context,String name) {
try {
// FileInputStream fis = context.openFileInput(name);
// File file = new File("filesdir", name);
File myFile = new File (path_file+File.separator+name);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
Bitmap b = BitmapFactory.decodeStream(fis);
//fis.close();
return b;
} catch(Exception e) {
return null;
}
}
Why does it work fine on older devices,But doesnt work on newer devices.

Access resource files in Android

I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Note this will return nothing, but will print the contents line by line as a DEBUG string in the log.
If you have a file in res/raw/textfile.txt from your Activity/Widget call:
getResources().openRawResource(...) returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile (it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...)); then read the content of the file as a stream

Categories

Resources