I am trying to load a file from the assets folder, the file name i want to be based on the current value of an int i (ie if i = 2 then open 2.txt and 2.jpg). I have the following code that deals with the asset manager side of things, and is working:
//link the image and text boxes to the xml
Image = (ImageView)findViewById(R.id.image);
Text = (TextView)findViewById(R.id.text);
loadDataFromAsset();
}
//actually load the text file and image file
public void loadDataFromAsset() {
//load the asset files themselves
try {
InputStream is = getAssets().open("1.txt");
//check file size
int size = is.available();
//create a buffer to handle it
byte[] buffer = new byte[size];
//send the data to the buffer
is.read(buffer);
//close the stream down
is.close();
//set the text we recovered to the TextView
Text.setText(new String(buffer));
}
catch (IOException ex) {
return;
}
//image file next
try {
InputStream ims = getAssets().open("1.jpg");
//load the image as drawable
Drawable d = Drawable.createFromStream(ims, null);
//set the drawable image to the imageview
Image.setImageDrawable(d);
}
catch (IOException ex) {
return;
}
}
I am new to java and dont really know how to move forward from here, how can i make the 1.jpg and 1.txt actually work based on the value of the int?
Thanks;
Andy
try this:
//actually load the text file and image file
public void loadDataFromAsset(int val) {
//load the asset files themselves
try {
InputStream is = getAssets().open(val + ".txt");
//check file size
int size = is.available();
//create a buffer to handle it
byte[] buffer = new byte[size];
//send the data to the buffer
is.read(buffer);
//close the stream down
is.close();
//set the text we recovered to the TextView
Text.setText(new String(buffer));
}
catch (IOException ex) {
return;
}
//image file next
try {
InputStream ims = getAssets().open(val + ".jpg");
//load the image as drawable
Drawable d = Drawable.createFromStream(ims, null);
//set the drawable image to the imageview
Image.setImageDrawable(d);
}
catch (IOException ex) {
return;
}
}
Try to use this for text
InputStream is = getResources().getAssets().open("yourINTvalue.txt");
String textfile = convertStreamToString(is);
Text.setText(textfile);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
for image try this
InputStream bitmap=null;
try {
bitmap=getAssets().open("yourINTvalue.png");
Bitmap bit=BitmapFactory.decodeStream(bitmap);
img.setImageBitmap(bit);
} catch (IOException e) {
e.printStackTrace();
} finally {
bitmap.close();
}
try like this
InputStream is = getAssets().open(i+".txt");
Related
i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.
I'm trying to do with this:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
But i am getting NullPointerException on the line is.close();
i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S
What am i doing bad? The file is called radiocd5.png and it is on the assets directory
You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.
I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun
// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}
Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.radiocd5
try {
InputStream istr = this.context.getAssets().open(P.strImage);
//set drawable from stream
this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
e.printStackTrace();
}
protected String openImageInAssets(String imageName) {
String encodedImageBase64 = "";
AssetManager assetManager = getAssets();
InputStream fileStream = null;
try {
fileStream = assetManager.open(imageName);
if (fileStream != null) {
// BitmapFactory.Options bfo = new BitmapFactory.Options();
// bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);
Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
// Convert bitmap to Base64 encoded image for web
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// to get image extension file name split the received
int fileExtensionPosition = imageName.lastIndexOf('.');
String fileExtension = imageName.substring(fileExtensionPosition+1);
// Log.d(IConstants.TAG,"fileExtension: " + fileExtension);
if (fileExtension.equalsIgnoreCase("png")) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// Log.d(IConstants.TAG,"fileExtension is PNG");
} else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
// Log.d(TAG,"fileExtension is JPG");
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
encodedImageBase64 = "data:image/png;base64," + imgageBase64;
}
} catch (IOException e) {
e.printStackTrace();
return encodedImageBase64="";
} finally {
//Always clear and close
try {
if (fileStream != null) {
fileStream.close();
fileStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
return encodedImageBase64;
}
Here is an alternative way
setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))
Another version, inside a fragment:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
Resources res = getResources();
img = (ImageView) root.findViewById(R.id.img);
AssetManager amanager = res.getAssets();
try {
InputStream imageStream = amanager.open("restaurant.jpg");
Drawable drawable = new BitmapDrawable(res, imageStream);
img.setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
This process seems much simpler in iOS/UIKit or iOS/SwiftUI.
I'm hitting an URL and saving the returned image response in cache dir. If I try to save Bitmap from Returned response inputstream then I get correct Bitmap. Now after saving that response inputstream in cache and after fetching it I'm getting null Bitmap
Write inputStream to cache dir -
String root = mContext.getCacheDir().toString();
String path = root + "/tomorrow.jpg";
try {
final File file = new File(path);
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) != -1)
output.write(buffer, 0, ch);
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
now I'm reading the file from cache dir -
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp1 = BitmapFactory.decodeStream(fin);
I'd like to thanks Dimitri Budiansky for guiding me. Fix as below-
//final byte[] buffer = new byte[1024];
//int ch;
//while ((ch = in.read(buffer)) != -1)
//output.write(buffer, 0, ch);
I commented above lines. Simply add below line.
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
for clarification u may check this Link
I have an xml file in my Android project.
It contains a simple list of employee ids.
I want to read the below xml content.
I placed this file in res/raw/
saplist.xml
<?xml version="1.0" encoding="UTF-8"?>
<EMPNOLIST>
<EMPID>“12345”</EMPID>
<EMPID>“23456”</EMPID>
<EMPID>“34567”</EMPID>
</EMPNOLIST>
Code to read it
{
// Load XML for parsing.
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("saplist.xml");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
String s = readTextFile(inputStream);
Log.e("FMApp: ", s);
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
This code doesn't read the xml content.
Instead, it crashes.
Could someone help me on how to read such a simple xml?
You can check http://developer.android.com/training/basics/network-ops/xml.html to read xml data.
You first closed the outputStream and then returned outputStream.toString() that isn't going to work.
private String readTextFile(InputStream inputStream) {
String result = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
result = outputStream.toString()
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return result;
}
consider i have 10 images in assets folder and i retrieve it to Image View.And i have added another 10 more images to assets folder.Will i be able to view all 20 images on image view?If not why?If so how?
This is the code that i used to read and copy assets file to SD card
String[] getImagesFromAssets() {
AssetManager assetManager = getAssets();
String[] img_files = null;
try {
// img_files = getAssets().list("pictures");
img_files = assetManager.list("pictures");
} catch (IOException ex) {
Logger.getLogger(GameActivity.class
.getName()).log(Level.SEVERE, null, ex);
}
return img_files;
}
void loadImage(String name) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("pictures/" + name);
File outFile = new File(getExternalFilesDir(null)+"/"+"pictures/"+ name);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
Bitmap myBitmap = BitmapFactory.decodeFile(outFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + "pictures/" + name, e);
return;
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
I recommend use 3rd party libs, Use Acceptable URIs examples in android Android-Universal-Image-Loader
Ex: String imageUri = "assets://image.png";
Credits: Sergey Tarasevich
i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.
I'm trying to do with this:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
But i am getting NullPointerException on the line is.close();
i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S
What am i doing bad? The file is called radiocd5.png and it is on the assets directory
You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.
I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun
// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}
Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.radiocd5
try {
InputStream istr = this.context.getAssets().open(P.strImage);
//set drawable from stream
this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
e.printStackTrace();
}
protected String openImageInAssets(String imageName) {
String encodedImageBase64 = "";
AssetManager assetManager = getAssets();
InputStream fileStream = null;
try {
fileStream = assetManager.open(imageName);
if (fileStream != null) {
// BitmapFactory.Options bfo = new BitmapFactory.Options();
// bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);
Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
// Convert bitmap to Base64 encoded image for web
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// to get image extension file name split the received
int fileExtensionPosition = imageName.lastIndexOf('.');
String fileExtension = imageName.substring(fileExtensionPosition+1);
// Log.d(IConstants.TAG,"fileExtension: " + fileExtension);
if (fileExtension.equalsIgnoreCase("png")) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// Log.d(IConstants.TAG,"fileExtension is PNG");
} else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
// Log.d(TAG,"fileExtension is JPG");
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
encodedImageBase64 = "data:image/png;base64," + imgageBase64;
}
} catch (IOException e) {
e.printStackTrace();
return encodedImageBase64="";
} finally {
//Always clear and close
try {
if (fileStream != null) {
fileStream.close();
fileStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
return encodedImageBase64;
}
Here is an alternative way
setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))
Another version, inside a fragment:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
Resources res = getResources();
img = (ImageView) root.findViewById(R.id.img);
AssetManager amanager = res.getAssets();
try {
InputStream imageStream = amanager.open("restaurant.jpg");
Drawable drawable = new BitmapDrawable(res, imageStream);
img.setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
This process seems much simpler in iOS/UIKit or iOS/SwiftUI.