Similar question to Android: Set a random image using setImageResource, but I think I'm looking for a different answer.
As mentioned in the linked post, this:
int p = R.drawable.photo;
image.setImageResource(p);
displays photo1, but something like this:
String a = "R.drawable.";
String b = "photo";
String c = a+b;
int p = Integer.parseInt(c);
image.setImageResource(p);
will not. I have a lot of images, and an array contining all of the image names, so I want to fill an array something like:
int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = ("R.drawable." + image_names[i]);
but I get a runtime error. Is there any way to make this loop work? Or better ways to cue up image ID's into an array?
Thanks!
You can use this method and it will retrun the source id based off a string. The second and third paramaters are optional but if you can put them in I would.
public int getIdentifier (String name, String defType, String defPackage)
Example:
int p = getIdentifier("photo","drawable")
Or if you are getting ids all the time you could create a function like:
public int getDrawableId(Context context, String name){
return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}
You just have to check to see if it returns 0 because that means it did not find it.
EDIT
For your example up there just impliment the function above and change it to this:
int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = getDrawableId(getApplicationContext(),"R.drawable." + image_names[i]);
Related
I have a data string name stringSplit that I want to split into 5 parts.
I use this to split the String:
String[] pisah = stringSplit.split(",", -1);
for (int i=0;i< pisah.length;i++) {
String hasil1 = pisah[0];
String hasil2 = pisah[1];
String hasil3 = pisah[2];
String hasil4 = pisah[3];
String hasil5 = pisah[4];
}
When the value in stringSplit there are 5 data (f.e: “data1,data2,data3,data4,data5”), the code is working properly. But when in stringSplit there are only one, two or three data, an exception will caught:
(f.e: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4).
And my question is how to handle the empty string? So even though the data only one, two, or three data the stringSplit still can be splitted.
I've tried by adding limit to -1 which this solution I got from another post, but still not working for me.
Editted:
I almost forgot, the result string (hasil1 - hasil5) will use for edittext.
fe: editText1.setText(hasil1);
and others.
One possible solution is to check if the index you are looking for is less than the length of the array. If that index is less than the size of the array than it definitely exists.
for (int i=0;i< pisah.length;i++) {
if(0 < pisah.length)
String hasil1 = pisah[0];
if(1 < pisah.length)
String hasil2 = pisah[1];
//similarly for all other idexes that you want the value for.
}
You have hard coded the number of EditText fields you can have! What if, there is a change in requirement, where you have to add another field? That would need you to add "editText6" and "hasil6" at a lot of places. The code is not nimble footed to changes in specs.
This is what I would do.
Create a list of EditText, say, textList
Iterate over the pisah array, and textist simultaneously and add the String at index i in pisah to the EditText object at index i in
textList.
This way, in case there are only 3 data values, you are automatically taking care of populating only 3 EditText objects.
This is the code :
List<EditText> textList;
String[] pisah = stringSplit.split(",", -1);
for (int i=0;i< pisah.length;i++) {
textList.get(i).setTest(pisah[i]);
}
use this code:
String res[] = new String[5];
String[] pisah = stringSplit.split(",");
for (int i=0;i< pisah.length && i < res.length;i++) {
res[i] = pisah[i];
}
if(res[0] != null )
//.......... res[0] valid
if(res[1] != null )
//.......... res[1] valid
if(res[2] != null )
//.......... res[2] valid
if(res[3] != null )
//.......... res[3] valid
if(res[4] != null )
//.......... res[4] valid
Here is the problem,
for (int i=0;i< pisah.length;i++) {
String hasil1 = pisah[0];
String hasil2 = pisah[1];
String hasil3 = pisah[2];
String hasil4 = pisah[4];
String hasil5 = pisah[5];
}
but that iterates over the list and gets the values in the list from 0-5 every time it loops, so what you should be doing is something like this
for(int i = 0; i < 6; i++){
if(i >= pisah.length()) break;
String hasilI = pisah[i];
}
This iterates over the list 6 times then if the list's size < 6 it will break out of the loop
I'm a bit of a newbie to programming. :P
I'm working with Processing right now to create a table of subjects with their ID, Title and Availability.
I have a 2D array that contains information like this:
units[0][0] = "CAKE100"; //Subject ID
units[1][0] = "Eating Cake And Baking Too"; //Subject Title
units[2][0] = "November"; //Subject Availability
units[0][1] = "TACO204"; //Subject ID
units[1][1] = "Tacos And Other Delicious Things"; //Subject Title
units[2][1] = "April"; //Subject Availability
units[0][2] = "KITC102"; //Subject ID
units[1][2] = "Kitchen Safety"; //Subject Title
units[2][2] = "June"; //Subject Availability
I'm trying to filter through the unit[0][x] section to find the index location of every Subject ID that has "1" in the fourth position of the string.
For example, I want to return [0] [0] and [0] [2], because "CAKE100" and "KITC102" both have "1" in the fourth position.
I've tried to use indexOf or .substring but for some reason I can't figure it out.
EDIT:
Not sure how much help it will be but here's my butchered code:
void checkLevel100() {
for ( int j = 0; j < units.length; j++) {
position = 0;
// position = units[0][j].indexOf("1"); //This returns 4;
if (units[0][j].substring(4) == "1") { //This doesn't run at all, and so it returns 0.
position = j;
}
fill(0);
text(position, width/2, height/2);
}
}
I also did what Kevin Workman suggested. Here is the code for that:
for (int i = 0; i < units.length; i++) {
if(units[0][i] == "TACO204"){ //This results in 1, as expected
location[i] = i;
println(i);
}
Once again, thank you for your time :)
You need to break your problem down into smaller steps.
Step 1: Loop over your 2D array. You might use a nested for loop for this.
To test that this step works, you might just print every element in your 2d array before worrying about any logic.
Step 2: Write an if statement that checks whether the value at that index passes your test.
To test that this step works, you might want to create a separate program that just tests a hardcoded value instead of using arrays.
Step 3: Once you have the first two steps working, then you can save the indexes that pass your test into some kind of data structure. You might us an ArrayList<Integer> for this.
Create a separate example program that just loops over an array without worrying about any logic. Create another separate program that just uses an if statement to test your condition against a hard-coded value. Then if you get stuck on a specific step, you can post a more specific question along with an MCVE. Good luck.
I think it would be simpler for you to store your subject's values as an object of a class. Perhaps store the numerical portion of the ID as an int too? Using a class will enable you to write more human readable code.
public class FoodSubject {
String stringID;
int numID;
String title;
String availability;
public FoodSubject(String stringID, int numID,
String title, String availability) {
this.stringID = stringID;
this.numID = numID;
this.title = title;
this.availability = availability;
}
}
To make a new array of your FoodSubject objects use this code:
FoodSubject[] subjectArray = new FoodSubject[3];
subjectArray[0] = new FoodSubject("CAKE", 100, "Eating Cake And Baking Too", "November");
Access the values like this subjectArray[0].numID
Look into overriding the toString() method in your class to print out all the values of your subject easily. This will help you identify problems in the rest of your code much easier!
If you still want to store the entire ID as a String use the charAt(int index) function to test if the character is a '1'.
This if (units[0][j].substring(4) == "1") { code is incorrect. Look at the String Java documentation for information on what substring does.
I posted this question up earlier and it was pretty much a lazy post as I didn't provide the code I had and as a result got negged pretty badly. Thought I'd create a new one of these ....
I have an array dogArray which takes ( name, secondname, dogname )
I want to be able to change the dogname:
here's my attempt :
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
String namgeChange = rp.next(); {
for (int i = 0; i < dogArray.length; i++){
for (int j = 0; j < dogArray[i].length; j++){
if (dogArray[i][j] == name){
dogArray[i][j] = nameChange;
}
}
}
}
For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.
Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?
Only one loop is necessary, also move your call to next.
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
for (int i = 0; i < dogArray.length; i++){
String nameChange = rp.next(); {
if(!dogArray[i].name.equals(nameChange)){
dogArray[i].name = nameChange;
}
}
}
You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.
I need to append to 2 HSSFRichTextStrings in Java with Apache POI. How can I do this?
What I'm exactly doing is I'm getting the rich text string already present in a cell and I'm trying to append an additional rich text string to it and write it back to the cell.
Please tell me how to do this.
It is possible to append two HSSFRichTextStrings, but you will have to do most of the work yourself. You will need to take advantage of the following methods in HSSFRichTextString:
numFormattingRuns() - Returns the number of formatting runs in the HSFFRichTextString.
getFontOfFormattingRun(int) - Returns the short font index present at the specified position in the string
applyFont(int, int, short) - Applies the font referred to by the short font index between the given start index (inclusive) and end index (exclusive).
First, create a little class to store formatting run stats:
public class FormattingRun {
private int beginIdx;
private int length;
private short fontIdx;
public FormattingRun(int beginIdx, int length, short fontIdx) {
this.beginIdx = beginIdx;
this.length = length;
this.fontIdx = fontIdx;
}
public int getBegin() { return beginIdx; }
public int getLength() { return length; }
public short getFontIndex { return fontIdx; }
}
Next, gather all of the formatting run statistics for each of the two strings. You'll have to walk the strings yourself to determine how long each formatting run lasts.
List<FormattingRun> formattingRuns = new ArrayList<FormattingRun>();
int numFormattingRuns = richTextString.numFormattingRuns();
for (int fmtIdx = 0; fmtIdx < numFormattingRuns; fmtIdx)
{
int begin = richTextString.getIndexOfFormattingRun(fmtIdx);
short fontIndex = richTextString.getFontOfFormattingRun(fmtIdx);
// Walk the string to determine the length of the formatting run.
int length = 0;
for (int j = begin; j < richTextString.length(); j++)
{
short currFontIndex = richTextString.getFontAtIndex(j);
if (currFontIndex == fontIndex)
length++;
else
break;
}
formattingRuns.add(new FormattingRun(begin, length, fontIndex));
}
Next, concatenate the two String values yourself and create the result HSSFRichTextString.
HSSFRichTextString result = new HSSFRichTextString(
richTextString1.getString() + richTextString2.getString());
Last, apply both sets of formatting runs, with the second set of runs being offset by the first string's length.
for (FormattingRun run1 : formattingRuns1)
{
int begin = run1.getBegin();
int end = begin + run1.getLength();
short fontIdx = run1.getFontIndex();
result.applyFont(begin, end, fontIdx);
}
for (FormattingRun run2 : formattingRuns2)
{
// offset by string length 1
int begin = run2.getBegin() + richTextString1.length();
int end = begin + run2.getLength();
short fontIdx = run2.getFontIndex();
result.applyFont(begin, end, fontIdx);
}
That should do it for concatenating HSSFRichTextStrings.
If you ever want to concatenate XSSFRichTextStrings, found in .xlsx files, the process is very similar. One difference is that XSSFRichTextString#getFontOfFormattingRun will return an XSSFFont instead of a short font index. That's okay, because calling applyFont on an XSSFRichTextString takes an XSSFFont anyway. Another difference is that getFontOfFormattingRun may throw a NullPointerException if there is no font applied for the formatting run, which occurs when there is no different font applied than the font that is already there for the CellStyle for the entire Cell.
If you're using XSSFRichTextStrings, you can't directly concatenate two RichTextString.
However, you can indirectly do so by finding the text value of the second RichTextString and then using the append method to append that string value with an applied font (RichText in essence).
XSSFRichTextString rt1 = new XSSFRichTextString("Apache POI is");
rt1.applyFont(plainArial);
XSSFRichTextString rt2 = new XSSFRichTextString(" great!");
rt2.applyFont(boldArial);
String text = rt2.getString();
cell1.setCellValue(rt1.append(text, boldArial));
Source:
enter link description here
So, let me explain the default situation at first: A user can choose a picture - and this picture is saved by a string (e.g. "picture1") in a Properties-file. Now I wan't to display the picture by loading the String off the Properties-file and getting the Image out of my Drawables-Resources by R.drawable.MYPICTURE.
this is what I worked out:
String iconsString[] = {"default", "icon"};
int iconsResource[] = {R.drawable.default, R.drawable.icon};
int iconResourcePosition;
int iconsStringLength = iconsString.length;
for (int i = 0; i < iconsStringLength; i++) {
if (iconsString[i] == mProperties.getProperty("icon")) {
iconResourcePosition = i;
} else {
iconResourcePosition = 0;
}
}
btn_profileIcon.setBackgroundDrawable(iconsResource[iconResourcePosition]);
But it doesn't work, since the ".setBackgroundDrawable" does not accept int-values. Well, and that's where I'm stuck. I could make the "iconsResource[]" beeing "Drawable" instead of "int", but that would cause an other problem :|
Thanks for the help!
mmmm don't you want to do something like this:
btn_profileIcon.setBackgroundResource(iconsResource[iconResourcePosition]);
Use BitmapFactory.decodeResource(…) to store a reusable Bitmap and then use setImageBitmap(…) on your ImageView (or derived).