Button Text and Booleans (Simple Android App) - android

I'm build the Fun Facts app on the Android Development Track. I decided to take a exploratory detour and try to create a very basic introductory message to the user. I changed the factTextView text to "You can click the button below to see a new fact!" and changed the showFactButton text to "Try it out!"
From there, I changed the final line onClick object (is that an object?) to the following:
public void onClick(View view) {
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
// Set button text to new fact prompt
showFactButton.setText("Show another fun fact.");
This seems to work fine. However, I feel like "updating" the button text to the same new string on every press isn't always the best practice, even if it is easy and readable. I tried to add a boolean that will check the text of the button, and update it only if it has not already been updated. This is what I've come up with so far:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public String launchText = getResources().getString(R.string.start_text);
public String nextText = getResources().getString(R.string.next_text);
public String buttonText = (String) showFactButton.getText();
public boolean updateLaunchText() {
if (buttonText.equals(launchText)) {
buttonText.replaceAll(launchText, nextText);
return true;
}
else {
return true;
}
}
public void onClick(View view) {
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
}
};
With the following added to strings.xml:
<string name="start_text">Try it out!</string>
<string name="next_text">Show another Fun Fact!</string>
No errors, but the button text stays on "Try it out!" I'm sure that all the extra objects are totally unnecessary compared to the first, working method for the scope of this app, but I'd still like to figure it out since I don't really have any idea what I'm doing with the boolean.
Questions: 1) What am I missing in the longer boolean approach? 2) What's the actual most efficient approach to accomplish this task?

Did you connect the listener to the button object?Without that connection no logic is applied to a button click.It goes like this:
buttonName.setOnClickListener(...)
You'd have to initialize the button object first though :)

Where r u call to method updateLaunchText() ?
you should change the objects to global object (not to create the into the listener):
private String launchText = getResources().getString(R.string.start_text);
private String nextText = getResources().getString(R.string.next_text);
private String buttonText = (String) showFactButton.getText();
and take the method updateLaunchText() out of the listener too.
and then into the onClick(View view) call to updateLaunchText() like this:
public void onClick(View view) {
updateLaunchText();
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
}

Related

Android JAVA navigate to fragment passing data with Navigation Component

I'm trying to navigate from a RecyclerView adapter to a detail fragment, passing an id value.
I can navigate from an item selected in the RecyclerView to open the GameDetailFragment using the following:
this.cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NavDirections action = ScoreboardFragmentDirections.actionScoreboardFragmentToGameDetailFragment();
Navigation.findNavController(v).navigate(action);
}
});
However, I can't seem to find how to pass data when clicking on the CardView item to the GameDetailFragment to query the details.
I can find many examples in Kotlin, but I'm just learning Java and Android and would rather not start with Kotlin.
Using the example from the documentation:
#Override
public void onClick(View view) {
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
ConfirmationAction action = SpecifyAmountFragmentDirections.confirmationAction();
action.setAmount(amount);
Navigation.findNavController(view).navigate(action);
}
It seems it's inaccurate as the documentation indicates that the word "action" is added to the END of the class name.
I decided to look at the actual generated class file, without modifying it, of course. The word "action" is added to the BEGINNING of the class file name or combination of the originating and receiving destinations.
The result:
this.cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strTemp = "todo";
ScoreboardFragmentDirections.ActionScoreboardFragmentToGameDetailFragment action = ScoreboardFragmentDirections.actionScoreboardFragmentToGameDetailFragment();
action.setMessage(strTemp);
Navigation.findNavController(v).navigate(action);
}
});
P.S. Have you ever even tried to follow along with the documentation? There is very little, if any, flow to their descriptions.
One paragraph they're talking about cats & dogs, then the next paragraph they talk about apples and oranges. As a noobie/beginner, it's incredibly frustrating because somehow you have to figure out how they all interconnect/interrelate to one another.
Then, when we ask, we get snooty responses referring right back to the same documentation. Like really...
But, what do I know, I'm only a beginner.

Can I change a URL using EditText and Button?

Here's the code that I want to change
private void updateQuestion() {
mQuestionRef = new Firebase("https://fdbfdb-d7cbb.firebaseio.com/"+
mQuestionNumber +"/question");
}
So can I add an EditText and Button beside it and the button will change the link (https://fdbfdb-d7cbb.firebaseio.com/) according to the value of the EditText, is that possible?
Yes obviously it's possible. Build the url during run time like keep your base url on a variable, and concat other part of url from edittext on button click then make network call or whatever you want.
String baseUrl = "https://fdbfdb-d7cbb.firebaseio.com/";
private void onClick(){
updateQuestion(edittext.getText().toString()) //Check edittext empty or not before this line
}
//////OR//////
private void updateQuestion(String number)
{ mQuestionRef = new Firebase(baseUrl+ number +"/question");
}
private void updateQuestion()
{
mQuestionRef = new Firebase("https://fdbfdb-d7cbb.firebaseio.com/"+ edittext.text.toString() +"/question");
}
Yes ofcourse
Method
private void updateQuestion(String questionNo) { mQuestionRef = new Firebase("https://fdbfdb-d7cbb.firebaseio.com/"+ questionNo+"/question");
}
Method usage
First convert your edit text into string like
String question = edittext.text.toString()
UpdateQuestion(question)
Now call the function on your button click or any where you want

gettext from edittext inside OnClicklistener doesn't work in android

Why can't i access the text from edittext via gettext
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString() != "") {
}
It says name has to be declared final. if so i cannot run the programm. Click doesn't work or application stops.
Declare your EditText and Button as global and initialize it
In java, when using == on two objects, you're not actually comparing the strings themselves. You'll need to use .equals(String) or .equalignorecase(String).
== actually compares the two object's references, not their values.
string1.equals(String target) compares the two strings based off of the actual characters in the strings.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString().equalsIgnoreCase("")) {
}
It has to be declared final inside the onCreate method, not above the onCreate mothed to get rid of all errors.
Either declare your edittext as final or as global.
Moreover, you should never use != for string comparison. It is prone to error. Change :
if(name.getText().toString() != "")
to :
if(!name.getText().toString().equals(""))
or in this specific case since what you actually care about is the string not being empty, you can use :
if(!name.getText().toString().isEmpty())

Accessing object from inside OnClick(view v)

I am attempting to create an application in Android.
I have a written a number of classes. The code below is the simplest of them, but it is sufficient to illustrate the problem I have not been able to solve.
public class Letter
{
private char letter;
public Letter( )
{
letter = ' ';
}
public void setLetter(char c)
{
letter = c;
}
public char getLetter( )
{
return letter;
}
}
I can define an object of this class with the following code: L = new Letter( );
If I want to set the value of letter, I can use the code L.setLetter(‘a’). Similarly, if I want to access this letter I can use the code L.getLetter( );
The problem is how to gain access to the letter object from inside OnClick(view v). The situation is further complicated by the fact that I need to perform the set operation on letter with one button and the get operation by another button.
Any help you can provide me will be greatly appreaciated.
I have solved the problem I proposed.
final Letter M = new Letter();
final New_Button button_Q = new New_Button(this);
button_Q.setText("Q");
button_Q.setId('A');
button_Q.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
char c = button_Q.getText( ).charAt(0);
M.setLetter(c);
}
});
Declaring my objects final was the key to developing the solution. Thank you francis for commenting on my code. Any further points you wish to add would be appreciated.

programming style with modal dialog

in my android application at some event in an activity I want to ask the user for a name (string). I know how to do this: call showDialog, create the dialog in the Activity.onCreateDialog method (I need to supply a string for the label) and handle the result in the onClick of the dialog. This works fine and to my satisfaction.
BUT this way I have three different places, where this simple task spreads throughout the code of my activity. I would much more prefer to keep this code together, to write some code like this:
string result;
if (showSimpleEditDialog(idForLabelString, result)==DIALOG_OK)
{
// do something with the result
}
or maybe with a class instance
SimpleEditDialog dlg = new SimpleEditDialog(idForLabelString);
if (dlg.showModal()==DIALOG_OK)
{
string result = dgl.getResult();
// do something with the result
}
(The "idForLabelString" would be some resource id for the label to use, DIALOG_OK would be some constant returned when the user clicks OK)
I know, I would have to write this methodes or this class. But for better readibility of my code I would do it. Any suggestions?
Thank you,
Gerhard
"BUT this way I have three different places, where this simple task spreads throughout the code"
So why don't you create a Method for this task? What you are talking about sounds like some sort of 'ActionListener' to me. This can be done in Java/Swing, but not in Android.
But, if you have three Dialogs, which all need to do the same when "YES" e.g. "NO" is pressed, you could define the 'DialogInterface.OnClickListener()' as a global inner-Class (or in a second class which extends the 'onClickListener') and then use it for all the Dialogs.
Now actually the problem with modal dialogs is mostly a problem with programm flow. You want to keep things together that belong together. You want to display a dialog that returns "ok" or "cancel" and additionaly e.g. a string that the user entered into one of the dialog widgets.
I do not want to write half of the code up to the line where I need the result of the dialog on one place and the rest of the code on another place namely the onClickListener of the dialog.
In some scenarios the first dialog might invoke a second dialog e.g. to specify a color which is not in the list of the first dialog's ListView.
Your code will be scattered all over the place (in each dialog's button onClickListener) and will be hard to read or to maintain.
Now after having written some unclear code like that I came up with the following solution which certainly respects the android design guides.
Instead of directly showing a dialog I create a Handler derived class which handles messages.
I send it a first message which creates and shows a dialog. It also forwards the handler to the dialog and the diaolg in it's onStop method sends another message to the handler, indicating the end of the dialog. There you can examine the dialogs properties, the contents of the edit fields or whether it was stopped with OK or CANCEL.
Now in the message handler all the logic of the task sits in different cases of the messages arg1 value.
Some cases might be skipped (e.g. the user selected a standard color and did not need a special color dialog).
The dialogs are independant of the scenario from which they are called and in their code only reflect their simple task (selecting from a list, some checkboxes etc.). They may be reused from other scenarios.
Following a kind of a template how to use this approach:
public class DoSomethingWithDialogs extends Handler
{
Context context; // from which it was called
final static int stepBegin = 0;
final static int stepNext = 1;
final static int stepSomethingElse = 2;
final static int stepLast = 3;
protected DoSomethingWithDialogs(Context context)
{
this.context = context;
}
public static void start(Context context)
{ // this is the main (only) entry point from outside
DoSomethingWithDialogs st = new DoSomethingWithDialogs(context);
st.sendMessage(st.obtainMessage(0, stepBegin, 0));
}
#Override
public void handleMessage(Message msg)
{
// step by step handling the task
switch (msg.arg1)
{
case stepBegin:
{
SomeDlg somedlg = new SomeDlg(context, this, stepNext);
// when the dialog closes, it sends a message to this with stepNext as arg1
somedlg.show();
}
break;
case stepNext:
{ // this message was send by the dialog when it finished
SomeDlg somedlg = (SomeDlg) msg.obj;
if (msg.arg2 == Dialog.BUTTON_NEGATIVE)
{
// has been canceled, nothing to do
} else
{
if (somedlg.someProperty)
{
} else
{
sendMessage(obtainMessage(0, stepSomethingElse, 0));
}
}
}
break;
case stepSomethingElse:
break;
}
}
}

Categories

Resources