I'm looking for a solution for my problem with automatic connection ImageView with a proper JPG from resources.
I have a simple array with names of gods like:
final String[] godslist = {"Achilles", "Agni", "Ah Muzen Cab", "Ah Puch", "Amaterasu", "Anhur", "Anubis", "Ao Kuang", "Aphrodite", "Apollo", "Arachne", "Ares", "Artemis", "Artio"}
final ImageView godImage = findViewById(R.id.godImage);
final TextView godName = findViewById(R.id.nameOfGod);
int randomGod = (int) (Math.random() * 14);
godName.setText(godslist[randomGod]);
And for now, it's working fine. In the TextView I get the random name of a god from the array.
The problem is with connecting chosen god with his image. I thought about a loop that will search resources by name of chosen god e.g. "Achilles". In resources, I have a file named "achilles.jpg" e.t.c., so it should be godName.setImageResource(R.drawable.achilles);. Not every god's name is consisting of one word only - like "Ah Muzen Cab" and drawable can't be named with spaces (but this is not a big problem for now). For some reasons drawable can't also be named starting with an uppercase character, so I probably need to do something like this:
godName.setText(godName.getText().toString().toLowerCase());
And then I should use some loop to find the name in resources. Below code should be easiest, if it would work like that, but...
godImage.setImageResource(R.drawable.(godName.setText(godName.getText().toString().toLowerCase())));
The same problem is with sounds from resources (depending on which god is randomly chosen), but it will be easier when I figure out how set images. Thank you for any help.
You can incapsulate data in a separate class, and use its instances when randomly choosing an array index:
public class GodData {
public final String name;
public final String imageResId;
public final String soundResId;
public GodData(String name, String imageResId, String soundResId) {
this.name = name;
this.imageResId = imageResId;
this.soundResId = soundResId;
}
}
final GodData[] godslist = {new GodData("Achilles", R.drawable.achilles, R.raw.achilles_sound), ...}
GodData randomGod = godslist((int) (Math.random() * 14));
godName.setText(randomGod.name);
godImage.setImageResource(randomGod. imageResId);
Related
I'm currently developing android quiz app and I implemented the "reset" button that resets the questions and randomize them, but I'm having trouble with calling the random Strings from .xml file in MainActivity.java.
I have all of my questions listed in the Strings.xml file like this, in order to make them easy to translate:
<string name="q1">The reactor at the site of the Chernobyl nuclear disaster is now in which country?</string>
<string name="a1">A. Slovakia</string>
<string name="b1">B. Ukraine</string>
<string name="c1">C. Hungary</string>
<string name="d1">D. Russia</string>
<string name="q1answer">B</string>
All of the questions are listed in that file like q1, q2, q3, and the same goes for ABCD answers: a1, b1, c1, d1; a2, b2, c2, d2, and so on.
There are many questions, but button chooses only 5 of them and displays them on the screen. The problem is that I just can't access the Strings if I want to use an integer generated by randomizer to find them in .xml:
for (int i = 1; i <= 5; i++) {
// I managed to get the identifier of the TextView with the for loop like that (TextViews for questios are listed q1q, q2q, q3q, q4q, q5q):
// I would like to do the same thing down there with Strings.
TextView question = (TextView) findViewById(getResources().getIdentifier("q" + i + "q", "id", this.getPackageName()));
// randomQuestion is the number of the question in random number generator from different method.
randomQuestion = randomizeNumbers();
// And here I'm stuck, this will show "q1-randomNumber" instead of the real question,
// because it does not see it as an ID. I tried various different solutions, but nothing works.
question.setText("q" + randomQuestion);
// I left the most silly approach to show what I mean.
}
What can I do to make the computer distinguish the name of the String? So it displays the real question instead of "q1" "q6" "q17"?
Thank you for help in advance!
You can access strings from the string.xml file by using the getIdentifier() utility.
private String getStringByName(String name) {
int resId = getResources().getIdentifier(name, "string", getPackageName());
return getString(resId);
}
It would be a lot easier if you also tried another approach entirely and create a Problem class which would look something like :
public class Problem(){
int ID;
String question;
String answer1; String answer2; //..and so on
String answerCorrect;
public class Problem(int ID, String question, ...){
this.question= question;
...
}
}
And than, create and ArrayList = new ArrayList<>(); and populate it with your questions. Than, you would have the ability to access them by their ID / position in array, search them by name and so on. In the future, you can use this model to request the list of problems from a server too.
question.setText("q" + randomQuestion);
In here, your parameter is inferred as a string since you pass "q", so it will display "q-randomNumber" as expected. I think what you want is to pass and actual ID to setText. To do this, you can do the same approach you did to find the question textview ID using "string" instead of "id".
In the MainActivity or in a function :
Resources res = getResources();
myString = res.getStringArray(R.array.YOURXMLFILE);
String q = myString[rgenerator.nextInt(myString.length)];
// WE GET THE TEXTVIEW
tv = (TextView) findViewById(R.id.textView15);
tv.setText(q);
// WE SET THE TEXTVIEW WITH A RANDOM QUESTION
And declare :
private String[] myString;
private static final Random rgenerator = new Random();
private TextView tv;
I am loading strings from a text file, eg;
Sunset Blvd 1950.ogg,Sunset Blvd,Paramount Pictures,1950,110,Billy Wilder,4,William Holden,Gloria Swanson,Erich von Stroheim,Nancy Olson
Now I have a class setup that extends from 2 parent classes (Media > Video > Avi/Ogg/etc). And that class holds the following variables;
public Avi(String title, String fileName, int releaseYear, String studio, String director, String castNames, double runtime, int cast) {
super(title, fileName, releaseYear, studio, director, castNames, runtime, cast);
}
Now I load the text file in using a buffer reader and a loop, but heres the problem, the cast names (Which come last in the text file, are also separated with commas but since I am using a splitter already I am not sure how to get every cast member into a simply string such as "Larry Davis,Eddy Murphy,Etc Etc" that can be returned later on. Also using a different splitter for cast names is not an option
if your cast starts at William Holden, you can do
line.split(",", 8);
I assume that by splitter you mean the String method "split".
If so, does your text file always have the same structure ?
Meaning is there always the same number of elements before the cast names ?
Because the String method "split" can take a second parameter specifying the number of elements to retrieve (cf. link to String API)
None of these solutions worked but heres what I came up with that worked:
String castNames = "";
int splitLength = split.length - 7;
for (int i = 0; i < splitLength; i++) {
castNames += split[7 + i] + ",";
}
Avi avi = new Avi(split[1]/*title*/
, split[0]/*filename*/
, Integer.parseInt(split[3])/*releaseyear*/
, split[2]/*studio*/
, split[5]/*director*/
, castNames/*castnames*/
, Double.parseDouble(split[4])/*runtime*/
, Integer.parseInt(split[6])/*cast*/);
return avi;
Having a symbol as the string separator as well as being valid data is not a good idea and results in code that is prone to errors. Of course you can work around that - some people before me have suggested ways to do it - but I strongly recommend that you change your input and remove the ambiguity.
I am newcomer to programming and I am attempting to create an Android app using Android Studio. I've tried searching but my findings do not appear to be what I am looking for, because they seem to be overly complex. What I've written below is just an example.
I want to be able to return a string from string.xml when user types "whale". The string in this case is information about the whale.
This is my java file, animal is already a string entered from a form.
TextView textview = new TextView(this);
String animalType = "water_" + animal; // This become water_whale if user typed whale
String animalInfo = getString(R.string.animalType); // This doesn't work
textView.setText(animalInfo);
This is my string.xml
<string name="water_fish">Fish is a small bla...</string>
<string name="water_whale">A whale is an enourmous blabla...</string>
<string name="land_giraffe">Africa.</string>
I have probably tunneled on this particular way and I have probably miss something obvious or is there another way to do this?
R.string.anyIdentifer represents an integer value. You can't add your own identifier with it, just the way you can't call any non existent property on any class. If you want to access any resource dynamically with it's name then there is a different approach for that.
Use this
TextView textview = new TextView(this);
String animalType = "water_" + animal;
int animalTypeId = getResources().getIdentifier(animalType, "string", getActivity().getPackageName())
String animalInfo = getResources().getString(animalTypeId);
textView.setText(animalInfo);
String string=getResources().getString(R.string.water_whale);
you can't use getString() method directly.
I've tried "\n\n" and "\r" and everything else, including replaceAll("\r\n", "n") and I still do not understand why it doesn't work. I've also tried "\w", "\n", "\n+" - I've basically tried everything under "My split("\n") doesn't work" on Google search.
I'm trying to split a word with a lot of "\n". I basically have two different classes. One generates this word, and via the other class constructor object transfers it into the split("\n") method. But whatever I do, the array still stays empty.
I've also tried word.split(System.getProperty("line.separator")) even though I didn't have a clue as to what it meant, but it also came up under one of the solutions to this problem.
Here's my Code:
//in Class A
public String getWord()
{
word = word +"\n" + horizontal;
return word;
}
//in Class B
classA a = new classA();
String grid = a.getWord();
String [] lines = grid.split("\n");
EDIT: Sorry, typo mistake, I'll just ask again later. I did actually put grid.split("\n") in my code. What now? The array really is empty. I did System.out.println(array.length) and it was 0. Also, I typed System.out.println("array is " + array) and it only gave me "array is" as output. I know I'm making a stupid mistake somewhere, and I know I can't expect people to answer my question if I don't know what info to provide.
I also wanted to add some stuff in the comments section here for the comfort of those sitting in front of their laptops...
word and horizontal is a string. It's actually a crossword puzzle together.
See? Look!
LONDONPYVRAOMNDDEFSG
GCPZVBATHYXAZXEZIMOZ
NKDGBERLINCHPLTMHMSM
ZMUKPGCHRKDTYGIMRLHO
TVRWBXPRETORIAJBVKWT
OGIVSDFULULHQHAHEJNV
PNWEJHBAKBJZNBPARIS
PHKCZCYGTXEEXDUCPMXF
QIMQMABRASILIALJOFJQ
GXNXKTAHIQMMIFPSYDLI
CAIROYKZYSWEFPUZPKRG
BTNAUNIDQAYVYAPGWWIN
QXZMQSZBTCBEIJINGBSD
QWQRYTBPTKRBCJUOMJTV
SODHAMSTERDAMEMSLVAM
YQHEVNXQQJXCDZKEYQVT
NAIROBISVDNTCFJNYDEG
AKXVOIGYTZTJHGIAFIKZ
BAGHDADSADJTWOOMVRYT
YCPOBXQQMQKBTDMYPYWT
It's city names. At the end of this, I'm supposed to show the solution to the puzzle by changing cases. I know how to do this, but the problem is that I can't seperate them into lines anymore. I don't know why. That's my only problem here. It seems to work for everyone, except for me.
Answers with clues will be appreciated? To delve into a dark and deep mystery...
It should be
grid.split("\n");
not
instance.split("\n")
Call grid.split("\n");
You can't split a class.
Better a.getWord().split("\n");
In your code there isn't no method named split , also your didn"t call your method getword inside System.out.println() ....
First Class :
public class A {
public String returnedWord ="";
public String getWord(String word , String horizontal)
{
returnedWord = word +"\n" + horizontal;
return returnedWord ;
}
}
the Second Class :
public class B {
public String word = "Hello";
public String horizontal = "World";
public static void main (String [] args ) {
A a = new A();
System.out.println(a.getword(word,horizontal));
}
}
you will get the output below :
Hello
World
Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}