Am trying to add icons to the grid dynamically based on the path provided by service,
i have added the icons inside the assets folder, am getting file not found exception, how can i fix it.
Below is my code,
try
{
InputStream im = context.getAssets().open(App.Path);
Drawable d = Drawable.createFromStream(im, null);
}
catch(IOException e)
{
e.printStackTrace();
}
I see you have "Profile Registration.png" -> rename the file so it does not contain spaces. Something like: "profile_registration.png"
Actually the problem is with prefix /assets/ :)
try {
String image = App.Path;
if (image.contains("/assets/")) {
image = image.replace("/assets/", "");
}
InputStream ims = getAssets().open(image);
Drawable d = Drawable.createFromStream(ims, null);
imageView.setImageDrawable(d);
} catch (IOException ex) {
return;
}
Please Check Your files availablity.
If Files there,do following instructions
Instead of
InputStream im = context.getAssets().open(App.Path);
please use this
InputStreamReader im = new InputStreamReader(getApplicationContext().getAssets().open("path name upto file")));
Please Use this.It will work
Try this:
try {
String image_path = App.Path;
String filepath = null;
if (image_path.contains("/ASSETS/")) {
filepath = image_path .replace(ASSETS, "");
}
InputStreamReader im = new InputStreamReader(getApplicationContext().getAssets().open(filepath)));
Drawable d = Drawable.createFromStream(ims, null);
imageView.setImageDrawable(d);
} catch (IOException ex) {
return;
}
Related
As part of my program, I need to show images belonging to a folder (JPG files). To accomplish that, I have this code:
private ArrayList<ImageGalleryItem> getData() {
final ArrayList<ImageGalleryItem> imageItems = new ArrayList<>();
try {
Intent intent = getIntent();
String imagesFolder = intent.getStringExtra("SourceFolder");
String questionId = Integer.toString(intent.getIntExtra("QuestionId", 0));
File file = new File(imagesFolder);
if (file.exists() && file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
try {
if (f.getName().startsWith(questionId + "_")) {
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
imageItems.add(new ImageGalleryItem(bitmap, f.getName()));
}
}
catch (Exception e)
{
Log.e("TDC#", e.getMessage());
}
}
}
}
catch (Exception e)
{
Log.e("TDC#", e.getMessage());
}
return imageItems;
}
The instruction "BitmapFactory.decodeFile(f.getPath());" creates the bitmap files for all files but for one of them. When that code is reached for the conflicting file, decodeFile throws an exception, but the stranger thing is that the exception is not catched by the try catch block.
When debugging using F7, the exception is thrown in BitmapFactory.java, in the throw shown in this code:
try {
bm = nativeDecodeByteArray(data, offset, length, opts);
if (bm == null && opts != null && opts.inBitmap != null) {
throw new IllegalArgumentException("Problem decoding into existing bitmap");
}
setDensityFromOptions(bm, opts);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
}
So the questions are, why the bitmap cannot be correctly decoded and why the exception is not catched.
If I browse for the file in mobile file manager, and open the file, it is shown correctly, so, there is no problem with the image format. Furthermore, this image was taken with the camera, the same as the other images that do decode correctly.
How to solve this problem or, is there an alternate way to do this?
I don't know why that happens. Try this:
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
I am trying to create a .txt file in android, I have tested a lot of options how to achieve this, I think the file is created but I can't find it, it should be writed somehow public in a public directory that I can access it.
Example:
cacheFile = new java.io.File(getFilesDir(), "cache.txt");
if(cacheFile.exists() && !cacheFile.isDirectory()) {
try {
writer = new FileWriter(cacheFile);
BufferedReader br = new BufferedReader(new FileReader(cacheFile));
String tempo;
while((tempo = br.readLine()) != null){
Log.i("TEST","Reading from cache "+tempo);
if (tempo.contains("http")) {
musicUrl.add(tempo);
}
else {
myDataList.add(tempo);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
Log.i("TEST", "Creating the cache ? " + cacheFile.createNewFile() + " in " + getFilesDir());
writer = new FileWriter(cacheFile);
} catch (IOException e) {
e.printStackTrace();
}
}
What other option I've tried: Android File on Internal Storage not found
you should use one of the following:
getExternalFilesDir()
getExternalStoargeDir()
the first will create a file in /sdcard/android/app.package/file
the second will be the root of /sdcard/
The call that you currently make, getFilesDir(), is returning the path in /data/data/app.package/file which is not accessable to anything other then your application.
I must transfer a data file necessary for my app.
I read many threads on the subject and I stll don't understand how it works.
1. I'm using android studio 0.8.6. A lot of threads mentions the folder assets which apparently resides in src/main. When I create a new project the folder doesn't exist. I create manually one and I put in it jpg and txt files.
2. I run the following code:
AssetManager am = getAssets();
String[] files = new String[0];
try {
files = am.list("Files ;
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
Toast.makeText(getApplicationContext(), "File: "+files[i]+" ", Toast.LENGTH_SHORT).show();
}
And I get a files.length = 0
1. I can create files, write in it and read it but I don know where they reside.
And that's not what I want to do. I want to pass the data with the app.
Sorry for the long email but I'm lost.
Thanks in advance!
The code I have used to read files from assets is listed below:
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
This code is not mine and can be found in the answers below:
read file from assets
I did some progress using the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
File dir = getFilesDir();
File f = new File("/data/data/com.example.bernard.myapp/");
File file[] = f.listFiles();
for(int i=0;i<file.length;i++){
Toast.makeText(getApplicationContext(), "File: "+String.valueOf(file[i]), Toast.LENGTH_SHORT).show();
}
}
I code in hard what seems to me like the root of my app:
File f = new File("/data/data/com.example.bernard.myapp/");
The result is I can see 3 files: lib, cache, files
in "files" appears the files I create running the app.
I still don't know where is assets, neither where I transfer/put the .txt and .jpg files I want to use with my app. I develop using studio.
I have a file food.jpg in assets folder. I have try many ways. but I still cannot get this image into imageView. when run, instead of display image "food.jpg", it displays image that I have declared in xml file. (that image is in drawable folder).
The first way is:
int asset_id = context.getResources().getIdentifier("food", "drawable", context.getPackageName());
imageView.setImageResource(asset_id);
The second way is:
AssetManager assetManager = context.getAssets();
InputStream istr;
try {
istr = assetManager.open("food");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Please teach me how to fix this problem.
thanks :)
Your code is working fine. just add image MIME-Type(.jpg,jpeg,.png... etc) in below line:
istr = assetManager.open("ceo.jpg");
full code for your refrance
AssetManager assetManager = getAssets();
InputStream istr;
try {
istr = assetManager.open("ceo.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
imageView.setImageBitmap(bitmap);
istr.close();
} catch (IOException e) {
e.printStackTrace();
}
Try this Code...
try {
// get input stream
InputStream ims = getAssets().open("food.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imgNews.setImageDrawable(d);
} catch (Exception ex) {
return;
}
}
Can you load a drawable from a sub directory in the assets (not the drawable folder) folder?
Hope this help:
Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
I recommend to use this
Drawable.createFromResourceStream(resources,new TypedValue(), resources.getAssets().open(filename), null)
which returns properly scaled drawable thanks to resources ...
Here's a class with static method to get the drawable from the assets. It also closes the inputstream.
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by bartburg on 4-11-2015.
*/
public class AssetsReader {
public static Drawable getDrawableFromAssets(Context context, String url){
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(url);
drawable = Drawable.createFromStream(inputStream, null);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return drawable;
}
}
Yes you can create a Drawable object from an InputStream using the createFromStream() method.
Here is function that does this for you.
Check the returned Drawable variable for null as null may return if the path is invalid or there is an IOException.
public static Drawable getDrawableFromAssetFolder(String fullPath, Activity ctx) {
Drawable d =null;
try {
d = Drawable.createFromStream(ctx.getAssets().open(fullPath), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}
This helped getting the right density
private Drawable drawableFromAssetFilename(String filename) {
AssetManager assetManager = mApplicationContext.getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(filename);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
BitmapDrawable drawable = new BitmapDrawable(mApplicationContext.getResources(), bitmap);
return drawable;
}
I was working in a RecyclerView adapter and found that David's answer was not working for me, (for some reason asset.open remained Unresolved no matter what I imported )
so I found this to work for me (Kotlin code)
val d = Drawable.createFromStream(context?.assets?.open("imageData/${imageName}.png"), null)
here is my directory, as you can see the assets start from the assets folder and here is a link on how to create that assets folder
At this version you can't, if you make a sub folder within your drawable folder you can't use it in your xml file, it won't be recognized when you use android:src.
Take a look at this thread: Can the Android drawable directory contain subdirectories?