I have the following code for getting a resource using name instead of id:
spec = new ImageView[56];
for (i=2; i<=56; i++) {
String s = null;
s = "items_r"+Integer.toString(i)+"_c1";
spec[i] = (ImageView) findViewById(getResources().getIdentifier(s,"drawable",getPackageName()));
Log.e(tag, Boolean.toString(spec[i] == null));
}
I have 56 items in my drawable folder named items_r1_c1 to items_r56_c1;
But I am getting spec[i] as null.
Could someone point me towards my error and how to correct it?
Thank you.
findViewById(int) is for finding Views that have already been inflated and that currently exist under your Activity's content view.
You'll want to use Resources.getDrawable(int) or ImageView.setImageResource(int).
spec = new ImageView[56];
for (i=2; i<=56; i++) {
String res = "items_r" + Integer.toString(i) + "_c1";
int resId = getResources().getIdentifier(res, "drawable", getPackageName());
spec[i] = new ImageView();
// Drawable image = getResources.getDrawable(resId);
// spec[i].setImageDrawable(image);
spec[i].setImageResource(resId);
Log.e(tag, Boolean.toString(spec[i] == null));
}
Try this
int id = findViewById(getResources().getIdentifier(s,"drawable",getPackageName());
spec[i] = (new ImageView()).setImageResource(id);
Related
I am trying to download some files in background, for that I used download manager and I made this method:
/*** media download ***/
public long mediaDownload(ArrayList<DownloadedFile> arrayList, String foldPathName) {
long downloadReference = 0;
// Create request for android download manager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
for (int i = 0; i < arrayList.size();i++){
DownloadManager.Request request = new DownloadManager.Request(arrayList.get(i).getUri());
request.setTitle("Data Download");
request.setDescription("New media");
//Set the local destination for the downloaded file to a path
//within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName, arrayList.get(i).getName());
File f = new File(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName + "/" + arrayList.get(i).getName());
Log.e("File:",f.toString());
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
}
return downloadReference;
}
I have a picture and a Video to download for test, and when checking downloaded file in Explorer I find 2 videos and 2 picture, debug that I found that onPostExecute method is called twice and I can't figure out why.
Here is my onPostExecute method:
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray region = null;
region = jsonObject.getJSONArray("regions");
Log.e("Regions:", String.valueOf(region.length()));
for (int i = 0; i < region.length(); i++) {
try {
JSONObject json_data = region.getJSONObject(i);
int height_view = Integer.parseInt(json_data.getString("height"));
int width_view = Integer.parseInt(json_data.getString("width"));
int left_view = Integer.parseInt(json_data.getString("left"));
int top_view = Integer.parseInt(json_data.getString("top"));
int right_view = Integer.parseInt(json_data.getString("right"));
int bottom_view = Integer.parseInt(json_data.getString("bottom"));
/**** Media in region ***/
JSONObject media = json_data.getJSONObject("media");
String type_media = media.getString("type");
url = media.getString("url");
name = media.getString("name");
uri = Uri.parse(url);
} catch (JSONException e) {
e.printStackTrace();
}
downloadedFiles.add(new DownloadedFile(name, uri));
}
Toast.makeText(MainActivity.this, "Layout Created with" + height + "x" + width, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Downloaded Files:",downloadedFiles.toString());
mediaDownload(downloadedFiles, folderName); // region media's download
}
On my logcat I see that my arrayList has 2 elements, but displayed twice, which means files are downloaded twice so the onPostExecute method called 2 times, thanks for help.
I figured out after passing my time debugging all the code, when the activity is created it changes the screen orientation and so it creates a second instance, so my AsyncTask is called twice and thats why i thought onPosteExecute is called twice, thanks for everyone who tried to help.
I am displaying almost 4,000 images in a loop with image name.
Here is the code which i am using to get my images from drawable folder
for(int i=0; i<count(images_array); i++) {
mDrawableName = images_array(i);
int resID = res.getIdentifier(mDrawableName, "drawable", activity.getPackageName());
Drawable drawable = res.getDrawable(resID);
image.setImageDrawable(drawable);
}
the issues are:
When the image name is not found in resource folder my app throws
me an exception and crashes.
Is there any better way to load 4000 images from drawable in
listview? Is there any way i can check if image is not in drawable
then show placeholder image ?
When the image name is not found in resource folder my app through me
an exception and crash.
This is not an issue since it is expected behavior that getIdentifier returns 0 for a non-existent resource and then getDrawable throws the Resources.NotFoundException for id = 0 (which is not a valid ID).
Is there any way i can check if image is mot in drawable then show
placeholder image?
You either catch that exception or check if getIdentifier returned 0.
I don't know the rest of your code, so based on what you posted, you could do this:
for (int i=0; i<count(images_array); i++) {
mDrawableName = images_array(i);
int resID = res.getIdentifier(mDrawableName, "drawable", activity.getPackageName());
Drawable drawable;
if (resID == 0) {
drawable = res.getDrawable(R.drawable.placeholderimage, null);
} else {
drawable = res.getDrawable(resID);
}
image.setImageDrawable(drawable);
}
Note:
getDrawable(int id) is now deprecated starting API 22.
In the sample code, I used getDrawable(int id, Resources.Theme theme) instead.
You might want to check out the other alternatives.
Is there any better way to load 4000 images from drawable in listview?
Try using Android's RecyclerView and/or 3rd-party libs such as Glide.
Boolean fileFound = true;
try{
int resID = res.getIdentifier(mDrawableName , "drawable", activity.getPackageName());
Drawable drawable = res.getDrawable(resID );
image.setImageDrawable(drawable );
}catch (Resources.NotFoundException e){
fileFound = false;
}
if(!fileFound){
int resID = res.getIdentifier("img_not_found" , "drawable", activity.getPackageName());
Drawable drawable = res.getDrawable(resID );
image.setImageDrawable(drawable );
}
I´m trying to load ".properties" files into a PropertyResourceBundle object
It´s working with this code, but I have to load a lot of different combinations.
static ResourceBundle res[] = {null, null, null};
res[i] = new PropertyResourceBundle(getResources().openRawResource(R.raw.respaul_de));
These files are in res/raw/ directory of my android project.
Does someone knows a solution to do it like that...
res[i] = new PropertyResourceBundle(getResources().openRawResource("R.raw." + <nameArray> + <languageArray>));
I´ve tried it like that...but it didn´t work. Because I get always an ID of "0".
int resID = getResources().getIdentifier("respaul_de", "id", getPackageName());
res[i] = new PropertyResourceBundle(getResources().openRawResource(resID));
I would be pleased if someone can help me.
EDIT:
Solution:
String n = resourceNames[i / 3].toLowerCase() + "_" + (lang[i % 3].toString()).toLowerCase();
int is = getResources().getIdentifier(n, "raw", getPackageName());
res[i] = new PropertyResourceBundle(getResources().openRawResource(is));
resolved:
int is = getResources().getIdentifier("respaul_en", "raw", getPackageName());
I have a problem that needs solving where we use OpenOffice 1.1.4 templated reports and programmatically export them to PDF.
The team who create the templates have recently changed the header image and some images in a table to background images (before they were just inserted) since this change the current program is not creating the PDFs with the images. We can export from OpenOffice manually and the images are included. Can anyone help with a change I may need to make to get these background images included please?
The current code:
private void print(XInterface xComponent,
PrintRequestDTO printReq, File sourceFile,
Vector<String> pages) throws java.lang.Exception {
String pageRange;
// XXX create the PDF via OOo export facility
com.sun.star.frame.XStorable pdfCreator = (com.sun.star.frame.XStorable) UnoRuntime
.queryInterface(
com.sun.star.frame.XStorable.class,
xComponent);
PropertyValue[] outputOpts = new PropertyValue[2];
outputOpts[0] = new PropertyValue();
outputOpts[0].Name = "CompressionMode";
outputOpts[0].Value = "1"; // XXX Change this perhaps?
outputOpts[1] = new PropertyValue();
outputOpts[1].Name = "PageRange";
if (printReq.getPageRange() == null) {
pageRange = "1-";
}
else {
if (printReq.getPageRange().length() > 0) {
pageRange = printReq.getPageRange();
}
else {
pageRange = "1-";
}
}
log.debug("Print Instruction - page range = "
+ pageRange);
PropertyValue[] filterOpts = new PropertyValue[3];
filterOpts[0] = new PropertyValue();
filterOpts[0].Name = "FilterName";
filterOpts[0].Value = "writer_pdf_Export"; // MS Word 97
filterOpts[1] = new PropertyValue();
filterOpts[1].Name = "Overwrite";
filterOpts[1].Value = new Boolean(true);
filterOpts[2] = new PropertyValue();
filterOpts[2].Name = "FilterData";
filterOpts[2].Value = outputOpts;
if (pages.size() == 0) { // ie no forced page breaks
// set page range
outputOpts[1].Value = pageRange;
filterOpts[2] = new PropertyValue();
filterOpts[2].Name = "FilterData";
filterOpts[2].Value = outputOpts;
File outputFile = new File(
sourceFile.getParent(),
printReq.getOutputFileName()
+ ".pdf");
StringBuffer sPDFUrl = new StringBuffer(
"file:///");
sPDFUrl.append(outputFile.getCanonicalPath()
.replace('\\', '/'));
log.debug("PDF file = " + sPDFUrl.toString());
if (pdfCreator != null) {
sleep();
pdfCreator.storeToURL(sPDFUrl.toString(),
filterOpts);
}
}
else if (pages.size() > 1) {
throw new PrintDocumentException(
"Only one forced split catered for currently");
}
else { // a forced split exists.
log.debug("Page break found in "
+ (String) pages.firstElement());
String[] newPageRanges = calculatePageRanges(
(String) pages.firstElement(), pageRange);
int rangeCount = newPageRanges.length;
for (int i = 0; i < rangeCount; i++) {
outputOpts[1].Value = newPageRanges[i];
log.debug("page range = " + newPageRanges[i]);
filterOpts[2] = new PropertyValue();
filterOpts[2].Name = "FilterData";
filterOpts[2].Value = outputOpts;
String fileExtension = (i == 0 && rangeCount > 1) ? "__Summary.pdf"
: ".pdf";
File outputFile = new File(
sourceFile.getParent(),
printReq.getOutputFileName()
+ fileExtension);
StringBuffer sPDFUrl = new StringBuffer(
"file:///");
sPDFUrl.append(outputFile.getCanonicalPath()
.replace('\\', '/'));
log.debug("PDF file = " + sPDFUrl.toString());
if (pdfCreator != null) {
log.debug("about to create the PDF file");
sleep();
pdfCreator.storeToURL(
sPDFUrl.toString(), filterOpts);
log.debug("done");
}
}
}
}
Thanks in advance.
Glad that suggestion of making the document visible helped. Since it has ALSO fixed the problem you have a timing/threading issue. I suspect you'll find that another dodgy option of doing a sleep before executing the save to PDF will also allow the images to appear. Neither of these solutions is good.
Most likley best fix is to upgrade to a newer version of Open Office (the API calls you have should still work). Another option would be to try to call the API to ask the document to refresh itself.
After finding the correct property I was able to open the file with the hidden property set to false, this meant when the file was exported to PDF it included the background images. Its a shame I could not find another solultion that kept the file hidden but at least its working.
I have the following:
getResources().getResourceEntryName(resourceId);
The problem is, that it retrieves only the file name without the extension.
For example, if I have the following res/drawable/pic.jpg, the
getResources().getResourceEntryName(resourceId);
is returning the value "pic". The extension .jpg is missing.
To get "res/drawable/pic.jpg" you could use this:
TypedValue value = new TypedValue();
getResources().getValue(resourceId, value, true);
// check value.string if not null - it is not null for drawables...
Log.d(TAG, "Resource filename:" + value.string.toString());
// ^^ This would print res/drawable/pic.jpg
Source: android/frameworks/base/core/java/android/content/res/Resources.java
You can do so
Field[] fields = R.raw.class.getFields();
for (int count = 0; count < fields.length; count++) {
// Use that if you just need the file name
String filename = fields[count].getName();
Log.i("filename", filename);
int rawId = getResources().getIdentifier(filename, "raw", getPackageName());
TypedValue value = new TypedValue();
getResources().getValue(rawId, value, true);
String[] s = value.string.toString().split("/");
Log.i("filename", s[s.length - 1]);
}
This should be the best solution:
TypedValue value = new TypedValue();
getResources().getValue(resourceId, value, true);
String resname = value.string.toString().substring(13, value.string.toString().length());
resname = "pic.jpg"
Short answer: You can't.
Another way to do this, would be to put your graphics inside the assets folder.
Then you can access the Files directly, without your App needing any permission.
You can, for example, do so in your Activity:
AssetManager am = this.getApplicationContext().getAssets()
InputStream is = am.open(foldername+"/"+filename)
Bitmap myNewImage = BitmapFactory.decodeStream(is);
I hope that this will accomplish what you had in mind.
UPDATE: it seems it is indeed possible, see Aleksandar Stojiljkovic's answer instead.