setImageResources - I would like to add a string. Possible somehow? [duplicate] - java

This question already has answers here:
Android, getting resource ID from string?
(14 answers)
Closed 9 years ago.
public void correctLetter(String Letter, int pos){
if(letter.equals("a")){
ImageView image = images[pos];
image.setImageResource(R.drawable.a);
image.setVisibility(ImageView.VISIBLE);
}
At the moment i got a method looking like this. But, when i got 26 letters, thats going to be a lot of ifs.
Anyone got an idea how i can change that? I tried doing something like this, but the setImageResource required int anyways.
public void correctLetter(String letter, int pos) {
char newLetter = letter.toCharArray()[0];
String startS = "R.drawable." + letter;
startS += Character.toString(newLetter);
ImageView image = images[pos];
image.setImageResource(startS);
image.setVisibility(ImageView.VISIBLE);
}

You can init startS by this way:
int startS = getResources().getIdentifier(letter, "drawable","com.yourpackage.name");

You can keep the resource ids for the images in a static int array and index into it while calling setImageResource(). Please refer to the code below
private static final int charImgIds[] = { R.drawable.a, R.drawable.b, ... , R.drawable.z };
public void correctLetter(String letter, int pos) {
int letterIndex = letter.toCharArray()[0];
ImageView image = images[pos];
image.setImageResource(charImgIds[letterIndex]);
image.setVisibility(ImageView.VISIBLE);
}

Related

How to make backspace on calculator? [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
How to remove the last character from a string?
(37 answers)
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 2 years ago.
I am making the calculator app.
I tried to make the delete button, but there are errors.
(1) If I press backspace when there is no number, the app closed suddenly.
(2) If I press a new number after deleting the number, the previous deleted number shows up again.
I searched a lot about it but I cannot understand them as a beginner.
I would appreciate it if you can explain it easily.
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
catch (ScriptException e) {
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
}
public void deleteOnClick(View view)
{
String del_number = workingsTV.getText().toString();
workingsTV.setText(del_number.substring(0,del_number.length() - 1));
}
Problem 1 is because del_number.length() is 0, so del_number.length()-1 is -1 which is an illegal parameter to substring. The easiest way to fix it is to not do anything if the length is 0.
Problem 2 is because you don't reset the variable workings when you delete. It needs to be set to "". Or don't have that variable at all and always use the workingsTV.getText() be the source of truth.
I found the solution.
I edit the code like this to prevent the app closed suddenly.
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}
But still I had a problem that the letter I deleted comes back when I press a new number.
The solution was this.
workings = workings.substring(0, workings.length() -1);
The letter at workings should be deleted as well like workingsTV
So here is full code for delete
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
workings = workings.substring(0, workings.length() -1);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}

"incompatible types: void cannot be converted to PLayer" what this meaning? [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 2 years ago.
I am currently working on java project and I am kinda stuck now and having problem.
I am java beginner and not understanding much.
I have problem with thePlayer. It is saying "incompatible types: void cannot be converted to PLayer"
Not sure what is wrong with my code. PLayer is class that I am having to pass values.
I hope get advices from expert. Thank you very much!
private void AddJButtonActionPerformed(java.awt.event.ActionEvent evt) {
final int MAX_NUMBER = 1000;
final double BET_COST = 100;
final double EXACT_MATCH = 10000;
final double THREE_DIGITS_MATCH = 3000;
final double TWO_DIGITS_MATCH = 2000;
final double ONE_DIGIT_MATCH = 1000;
{output.delete(0,output.length());
String selectedPlayerName = jList2.getSelectedValue();
PLayer thePlayer;
thePlayer = searchmusic(selectedPlayerName);
if(numberAsString.length() > 0 && !numberAsString.equals("")&&
numberAsString != null && thePlayer != null &&
thePlayer.getBalance() >= BET_COST)
You declared thePlayer to be of type Player:
Player thePlayer;
But you assign it the return of a function called searchmusic. You didn't show the searchmusic function but quite likely, it is defined like:
void searchmusic(String selectedPlaydName) {
// The code of the function
}
That function shall return a Player, not void. void means that the function return nothing.

EditText must have at least 10 characters? [duplicate]

This question already has an answer here:
EditText Minimum Length & Launch New Activity
(1 answer)
Closed 8 years ago.
I am a new developer on Android and Java. How can I make at least 10 characters in EditText ? Also, when the user enter a value less than 10, the application send an error message on screen. How can I do these ? [ edittext > = 10 ]
Use something like this:
EditText et = (EditText) findViewById(YOUR_EDITTEXT);
String s = et.getText().toString();
if(s.length() <= 10){
et.setError("Must exceed 10 characters!");
} else {
// ...
}
You can do that in several ways, but you can try this way:
if (myEditText.getText().length() < minLength) {
//Your message to there is no enough caracters
} else {
//Your action if it is satisfied.
}
You can set minLenght to 10, or whatever, or simply ask if value is less than 10.
I hope that you get idea from this.
You can use text watcher to check the user input and decide what to do inside
EditText editText = new EditText(this);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Yo can validate your TextView and if it doesn't fit your requirements, use myTextView.setError(String) to show an error.
If not you will have to implement myTextView.addTextChangedListener(...) and do things manually.
Hope it helps.

How to check when two object collisions [duplicate]

This question already has answers here:
Collision Detection with MANY objects
(3 answers)
Closed 9 years ago.
I have two moving image views in a little game I'm making,
anyway they are always in the same Y so im just want to check when they are in the same x
any help?
int [] object1Position = new int[2]; // declare int array for x,y object position
int [] object2Position = new int[2]; // the same
imageView1.getLocationOnScreen(object1Position); // get imageView1 position
imageView2.getLocationOnScreen(object2Position); // get imageView2 position
public boolean checkColisionOnXAxis()
{
if (object1Position[0] == object2Position[0] )
return true;
return false;
}
just an idea.. but you need to get at each time the current location of the objects..
so you need timer or something like that to get the current position

I know I am getting a stackoverflow because I am using recursion but is there an easy way to get round this?

I want to add an image to an ImageButton depending on a number between 0 and 10. My getNumber method is:
public int getNumber(){
// get a random number between 0 and 10
Random randomNumber = new Random();
num = randomNumber.nextInt(10);
return num;
}
I want every image to be unique but the problem I was having was that if numList did contain num it just would leave the button blank. I've tried to call permuteButton again recursively until num is not contained within my list but this does not seem to work.
public void permuteButton(ImageButton btn){
getNumber();
for(int i=0; i<=numList.size(); i++){
//check if the number is already being used
if( numList.contains(num) ){
permuteButton(btn);
}
// else the list doesnt have the number so assign the picture and add number to list
else{
numList.add(num);
assignPictures(btn);
}
}
}
Any help would be appreciated. I'm sorry if this is a simple question.
There are various things wrong with this code:
It would be better to have a single instance of Random instead of creating a new instance on each call to getNumber()
Rather than changing an instance variable within getNumber(), it would be sensible to just return the value and assign that to a local variable in permuteButton
Instead of recursion, you could use a while loop in permuteButton:
int num = getNumber();
while (numList.contains(num)) {
num = getNumber();
}
numList.add(num);
assignPictures(btn); // Presumably you'd now want to pass in num too
It would probably be a better idea to just shuffle the list to start with, create a Queue from it, then you can just take an item from the queue each time you need one. (This would also make it very easy to spot when you've used them all)
My answer is similar to the last suggestion from Jon Skeet.
// might be more than 10 ImageButtons, with only 10 images
for (ImageButton imageButton : imageButtons)
imageButton.putImage(randomImage.next());
...
public class RandomImage {
private final List<Image> shuffledImages;
private int currentIndex;
public RandomImage(List<Image> images) {
shuffledImages = new ArrayList<>(images.size());
shuffledImages.addAll(images);
currentIndex = -1;
}
public Image next() {
currentIndex++;
if (currentIndex % shuffledImages.size() == 0) {
currentIndex = 0;
Collections.shuffle(shuffledImages);
}
return shuffledImages[currentIndex];
}
}

Categories