Android beginner onClick crash - java

I'm programming Android for the first time and I'm having some difficulties. The idea is to make a guessing game app in which the user takes a number in his/her head and the app tries to guess it. The user will give hints like higher and lower to the app. For some reason the app crashes after I press the start button. Because of this, I know that there is an error in the onClick method but since it shuts down immediately after I press the start button, I can't use something like a println to debug.
So actually I have 2 questions:
Where does my reasoning fail? (or show me how to figure out my mistakes)
How can I debug things like this?
The start, higher and lower are all buttons in the program.
#Override
public void onClick(View arg0) {
int min = 0;
int max = 100;
Random random = new Random(100);
int answer = 0;
if (arg0 == start) {
answer = random.nextInt(100);
buttonTextView.setText(answer);
}
else if (arg0 == higher){
min = answer;
answer = random.nextInt((max - min) + min);
buttonTextView.setText(answer);
}
else if (arg0 == lower) {
max = answer;
answer = random.nextInt((max-1) - min);
buttonTextView.setText(answer);
}
}

where does my reasoning fail?
You are using the wrong setText() method. In the TextView Docs you will see that there is one which takes an int, this is for retrieving a String resource that you have in your strings.xml so you would pass it a resource id. So your setText() is looking for a resource with the id of whatever your answer variable is. You will want to convert this to a String with something like
buttonTextView.setText(String.valueof(answer));
or one of several different ways.
How can I debug things like this?
When your app crashes there will be an exception in your logcat. This answer can help you to read your logcat. To open your logcat window in Eclipse, if it isn't already, you can do this
Window --> Show View --> Other --> Android --> LogCat
A couple side notes
You should change your params like in onClick() to something meaningful so I would change
public void onClick(View arg0)
to something like
public void onClick(View v) // v for view, could also be view, btn
// whatever makes sense to you and others who may read it
You also should compare the id of your View clicked instead of the View itself. So you would compare it with something like the following (assuming you changed arg0 to v)
if (v.getId() == R.id.start) // Assuming start is the id in your xml of your Button
// this will also allow you to use a switch statement
Your variables in onClick() (min, max, and answer) should be initialized outside of onClick() or they will be reset to the default values with each click which I'm pretty sure you don't want (thanks to 323go for pointing that out).

Related

Changing Background based on update of TextView

I am trying to create a simple android app using JAVA(Android Studio). What I am willing to implement is the background color of the app to change based on the content of the TextView (which is updated constantly between two values "Open" and "Closed"). I have seen that onChanged() must be used but I don`t really understand how to Implement the listener for the TextView.
I tried wrote this :
measurementValue = (TextView) findViewById(R.id.textbox_main); measurementValue.addTextChangedListener(new TextWatcher() {}
based on what I have found online, but can`t really figure out what the next step is. I am a total newbie so please be kind.
Best regards!
You can listen for text change on those 3 callbacks. It depends on your use case.
#Override
public void onTextChanged(CharSequence textInput, int start, int before, int count) {
String strInput = textInput.toString();
if ("open".equalsIgnoreCase(strInput)) {
// text is "open"
// change background to desired color
} else if ("closed".equalsIgnoreCase(strInput)) {
// text is "closed"
// change background to desired color
}
}

Android programming: How to make language change permanent in onItemSelected adapter in a spinner

I'm new to android programming and I would like to do the following:
I have a spinner which lets you change language. I have set it up and it works quite well. However the issue is that it does not remember the chosen language (in the spinner). So if you were to close the app and restart it, it will revert to the first item on the spinner which is english.
I want to change the function in such a way that once you select an item, it remembers it.
I've set up a shared preference which remembers which language is picked. However I can't make the shared preference the lead since then I could never change the chosen language, and if I make the chosen language the lead then the preference will always follow the chosen language even at the start where the chosen language should actually follow the preference. Here's the code that I have now. I hope anyone can help me we this since I've been breaking my brain over it for a while now
pref_language = pref.getString("language", "en");
//pref_language_begin = pref.getBoolean("language_begin", false);
final Spinner spinner_languages = (Spinner) findViewById(R.id.spinner_languages);
spinner_languages.setAdapter(new CustomSpinnerAdapter(MainActivity.this, R.layout.customspinneritem, languages, language_flags));
spinner_languages.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
language_chosen = (String) parent.getItemAtPosition(position);
if (!pref_language.equals(language_chosen)) {
SetLocale(language_chosen);
pref_language = language_chosen;
edit.putString("language", pref_language);
//edit.putBoolean("language_begin", true);
edit.apply();
recreate();
}
else{
}
}
The customspinneradapter is just there to let me select both a language and a flag for it.
I think I might need a second preference but I have no idea on how to implement it. The leading language at start up should be the preference but the language after choosing one in the spinner should be the chosen language. I was thinking about using an onclick listener but I'm not sure I should with spinners.
Surely there must be a more simpler way and I'm just not thinking straight.
Hope you guys can help me out!
I will give you couple suggestions..
Name your variables with the "cammel case" technique. For example:
spinner_languages shoud be named spinnerLanguages . Be a pro :)
Make a key for languages in shared preferences as a global and constant variable to use it everywhere in a class or classes and prevent typo mistake (if you don't know what is 'global variable" please google it):
static final String LANGUAGES_KEY = "languages";
Just when you start your activity ( onCreate() method but before super.onCreate(savedInstanceState); ) read your shared preferences and set language to the app:
// language from android system
String langSystem = Locale.getDefault().getLanguage();
String lang = sharedPreferences.getString(LANGUAGES_KEY, langSystem);
// update language
SetLocale(lang);
After that find the right language index for spinner (for example by using for loop)
and use:
spinnerLanguages.setSelection(languageIndex)
just use setSelection method for initial selecting item after setting adapter (position must be smaller than list items count, without adapter set spinner have 0 items)
spinner_languages.setSelection(position);
position may be picked e.g. by iterating through languages array (passed to adapter) and comparing each lang to pref_language
int position = -1;
for(int i=0; i < languages.size(); i++) {
if(pref_language.equals(languages.get(i))){
position = i;
break;
}
}
if (position >=0) { // found
spinner_languages.setSelection(position);
}
check out THIS topic about spinner selection

Can && be used in if statements?

Im working on an app that converts a currency. I need it so that the user can enter an amount and then select one button which will have a specific material on it and then the user will click another button to convert it to another material. Eg copper converted into silver. But when I run the program for some reason when I click the calculate button nothing happens on the screen and no errors appear. Is it because I'm using && or something else I am very confused as to why it is not working. Here is my code:
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
btCalculate.setText(convert);
}
}
});
}
}
&& means and -- so both buttons have to be pressed at the same time for the if to evaluate to true? Not sure if this is what you intended to do.
When trying to figure out what is going wrong in your code you can use print statements or the debugging option in your IDE to step through your code line by line to see where the problem occurs.
I added a couple print statements to your code to show whether btCopper1 and btSilver2 are pressed and another print statement showing that the btCalculate() method will be called. If nothing prints to the console window at all then you aren't even reaching the onClick() method and something else went wrong before the portion of code that you posted.
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("btCopper1="+btCopper1.isPressed() + " btSilver2="+btSilver2.isPressed());
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
System.out.println("btCalculate is called");
btCalculate.setText(convert);
}
}
});

Java Android Badge Drawable not working properly after configuration change

I have a Bottom Navigation view with a badge drawable that shows new chats.
This badges are updated upon a listener to Firebase database, where I store the notification counter. When this value change, the badge is updated. Moreover if the counter is equal to zero, the badge is set not visible.
Everything works fine except if I change some configuration using the device Settings (such as language or removing permissions). In fact, if I do that and go back to the app, the activity is re-created (sometimes without destroying it) and badge reloaded. But the setVisibility seems not working. Even if the counter is zero the badge is visible. Plus is not update anymore when the listener is triggered.
The code works, I checked with some logs if the listener is triggered and if the lines which include setVisibility are run. It just seems to have random behaviour.
If the activity is destroyed and recreated again, it works.
Any help will be appreciated!
this is how I initialize the badge
bottomNav = findViewById(R.id.bottom_navigation);
badge_chat = bottomNav.getOrCreateBadge(R.id.nav_chat);
badge_chat.setVisible(false);
this is the listener code
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
int badge_counter = dataSnapshot.getValue(int.class);
boolean visibility;
if (badge_counter == 0) {
visibility = false;
} else {
visibility = true;
}
badge_chat.setNumber(badge_counter);
badge_chat.setVisible(visibility);
}
One way I've managed to resolve this is to create/remove badge whenever it needs to be visible/hidden. In your case, something like this should work:
if (badge_counter == 0) {
getBadge(R.id.nav_chat)?.isVisible = false
removeBadge(R.id.nav_chat)
} else {
getOrCreateBadge(R.id.nav_chat).apply{
isVisible = true
number = badge_counter
}
}
note: the answer is in Kotlin.

Click on a button to chance textfield 50% chance

im very new to java & android development,
I want a textfield that changes 50% to "You win!" or 50% to "You Lose!" when i click/tap a button.
And a image rotating randomly, like it is 0° then it will get a number between 0 and 100 (higher then 50 is clockwise lower then 50 is counter-clockwise)
i might be asking to much xD but i really dont know how i do this.
How do i do this ?
I actually dont want very advanced answers because im very new to java.
Theres is pretty much nothing in my code except for a button and a textfield.
Here a little help to start off.
First you should add an OnClickListener to your button:
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleButtonClick();
}
});
The handleButtonClick()-method could look like this:
private void handleButtonClick() {
// Here we get a random integer between 0 and 99 (including 0 and 99)
int randomNumber = new Random().nextInt(100);
// Here we check if the random number is even
boolean isEven = randomNumber % 2 == 0;
// Now you can do stuff depending on the integer itself (rotation)
// and depending on whether it's even or not.
if(randomNumber < 50){
// do this
} else {
// do that
}
if(isEven){
// do this
} else {
// do that
}
}
To change the text you use:
yourText.setText(...);
But this is really basic stuff you could read on Android TextView
And rotating images was discussed here Android: Rotate image in imageview by an angle
Please read tutorials or refer to this before asking every little thing you could easily look up. Feel free to ask again when you get stuck.
Good luck.
Math.random() method gives you a floating point number between 0-1 but not included 1.
All you have to do is:
int randomNumber = (int)(Math.random()*101);
if(randomNumber < 50)
...
else
...

Categories

Resources