Inject CSS from url Android Studio - android

I'm using an InjectCSS script to use an extra css file on a webview.
But the script takes the CSS file from the assets folder, I want the css file externally hosted.
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
wv.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})();");
} catch (Exception e) {
e.printStackTrace();
}
}
I tried to change the inputstream to url but that didnt work.
InputStream inputSteam = new URL("http://www.website.com/folder/style.css").openStream();

If you need to use BASE64-encode, you need this
InputStream inputSteam = new URL("http://www.website.com/folder/style.css").openStream();
String encoded = new String(readBytes(inputStream), Base64.NO_WRAP);
// ...
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}

Related

Is there a way to convert audio files to byte array in android studio

I'm trying to store an audio file that is picked by the user from his own music player into sqlite database and I want to know is there a way to convert audio files to byte array.
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] arr = readByte(inputStream);
Log.d("byte: ", "" + Arrays.toString(arr));
or
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
try {
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] myByteArray = getBytesFromInputStream(inputStream);
// ...
} catch(IOException e) {
// Handle error...
}

using inflater and deflater to compressmore than one time

I am using inflater and deflater to compress and uncompress bytes later
I was compressing bytes and it was working so good, but I had problem that the bytes still have a little big size.
So I thought in compressing it twice times, but I am getting error
date formation exception.
and this is my code to compress and uncompress:
public static byte[] compress(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer); // returns the generated code... index
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] output = outputStream.toByteArray();
//LOG.debug("Original: " + data.length / 1024 + " Kb");
// LOG.debug("Compressed: " + output.length / 1024 + " Kb");
System.out.println("original" + data.length/1024 +"kb");
System.out.println("compressed" + output.length +"b");
return output;
}
public static byte[] decompress(byte[] data) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = 0;
try {
count = inflater.inflate(buffer);
} catch (DataFormatException e) {
e.printStackTrace();
}
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
System.out.println("original revived" + data.length/1024 +"kb");
System.out.println("uncompressed" + output.length/1024 +"kb");
return output;
}
and i compress like this:
byte data[] = compress(byteArrayOutputStream1.toByteArray());
byte data_2[] =compress(data);//////double compress
and I uncompress this way:
byte[] us =decompress(s);
byte[] us2 =decompress(us);

Android bluetooth client receive xml

I'm new at android development and I'm creating simple bluetooth app that can receive xml file and save xml file values to database. But how can I receive xml file from bytes array? Is it possible? After searchinf I found this question and based ont that question I try to save byte array to file. But how I need to test it? I can't find my file in my phone.
case Constants.MESSAGE_READ:
byte[] readBuffer = (byte[]) msg.obj;
try {
String path = activity.getFilesDir() + "/myFile.xml";
Log.d("MuTestClass", path);
FileOutputStream stream = new FileOutputStream(path);
stream.write(readBuffer);
stream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
You can use:
class Utils{
public static InputStream openFile(String filename) throws IOException{
AssetManager assManager = getApplicationContext().getAssets();
InputStream is = null;
is = assManager.open(filename);
return new BufferedInputStream(is);
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
like this:
try {
Utils.readBytes(Utils.openFile("something.xml"));
} catch (IOException e) {
e.printStackTrace();
}

Reading a resource sound file into a Byte array

I have cheerapp.wav or cheerapp.mp3 or some other format.
InputStream in = context.getResources().openRawResource(R.raw.cheerapp);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
// Create a DataInputStream to read the audio data from the saved file
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[??];
int i = 0; // Read the file into the "music" array
while (dis.available() > 0) {
// dis.read(music[i]); // This assignment does not reverse the order
music[i]=dis.readByte();
i++;
}
dis.close();
For the music byte array which takes the data from the DataInputStream. I don't know what the length of that to allocate.
This is raw file from resource not a file therefore I wouldn't know the size of that thing.
You do have byte array length as you can see:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
And then you can read whole Stream into byte array easily.
Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Hope it will help.
Create an sdcard path:
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
Convert as a file and have to call the byte array method:
byte[] soundBytes;
try {
InputStream inputStream =
getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
soundBytes = new byte[inputStream.available()];
soundBytes = toByteArray(inputStream);
Toast.makeText(this, "Recordin Finished"+ " " + soundBytes, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
method:
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
In Kotlin use
InputStream.readBytes()

Image Uri to bytesarray

I currently have two activities. One for pulling the image from the SD card and one for Bluetooth connection.
I have utilized a Bundle to transfer the Uri of the image from activity 1.
Now what i wish to do is get that Uri in the Bluetooth activity to and convert it into a transmittable state via Byte Arrays i have seen some examples but i can't seem to get them to work for my code!!
Bundle goTobluetooth = getIntent().getExtras();
test = goTobluetooth.getString("ImageUri");
is what i have to pull it across. What would be the next step?
From Uri to get byte[] I do the following things,
InputStream iStream = getContentResolver().openInputStream(uri);
byte[] inputData = getBytes(iStream);
and the getBytes(InputStream) method is:
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Kotlin is very concise here:
#Throws(IOException::class)
private fun readBytes(context: Context, uri: Uri): ByteArray? =
context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
Kotlin has convenient extension functions for InputStream like buffered,use , and readBytes.
buffered decorates the input stream as BufferedInputStream
use handles closing the stream
readBytes does the main job of reading the stream and writing into a byte array
Error cases:
IOException can occur during the process (like in Java)
openInputStream can return null. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.
Syntax in kotlin
val inputData = contentResolver.openInputStream(uri)?.readBytes()
Java best practice: never forget to close every stream you open!
This is my implementation:
/**
* get bytes array from Uri.
*
* #param context current context.
* #param uri uri fo the file to read.
* #return a bytes array.
* #throws IOException
*/
public static byte[] getBytes(Context context, Uri uri) throws IOException {
InputStream iStream = context.getContentResolver().openInputStream(uri);
try {
return getBytes(iStream);
} finally {
// close the stream
try {
iStream.close();
} catch (IOException ignored) { /* do nothing */ }
}
}
/**
* get bytes from input stream.
*
* #param inputStream inputStream.
* #return byte array read from the inputStream.
* #throws IOException
*/
public static byte[] getBytes(InputStream inputStream) throws IOException {
byte[] bytesResult = null;
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
bytesResult = byteBuffer.toByteArray();
} finally {
// close the stream
try{ byteBuffer.close(); } catch (IOException ignored){ /* do nothing */ }
}
return bytesResult;
}
use getContentResolver().openInputStream(uri) to get an InputStream from a URI. and then read the data from inputstream convert the data into byte[] from that inputstream
Try with following code
public byte[] readBytes(Uri uri) throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Refer this LINKs
This code works for me
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
public void uriToByteArray(String uri)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
int n;
try {
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = baos.toByteArray();
}
Use the following method to create a bytesArray from a URI in Android studio.
public byte[] getBytesArrayFromURI(Uri uri) {
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}catch(Exception e) {
Log.d("exception", "Oops! Something went wrong.");
}
return null;
}

Categories

Resources