Accessing object from inside OnClick(view v) - android

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.

Related

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())

Check if a resource id from view in array is displayed and click on it (Android-Espresso)

I have the following case. We are using the Gherkin language to drive our native ui automation with Espresso. In our Gherkin lines we've got a line called:
And I tap on button "Next"
Where "Next" is a variable String we pass into our glue code (we are using the Cucumber framework).
As it happens, our app has many "Next" buttons with different resources ids. I ended up by using gherkin lines with variables like:
And I tap on button "Next in screen 1"
And I tap on button "Next in screen 2"
Now I want to use only the Gherkin variable "Next" in my code. I get an Integer array which contains all the resources ids from all the Next buttons, but when I want to check which id is displayed on the screen I got a NoMatchingViewException.
This is my current solution for now:
final int[] uiElementIds = getArrayWithIdsFromUIElement("Next");
int testId = 0;
for(int id : uiElementIds) {
try {
onView(withId(id)).check(matches(isDisplayed()));
testId = id;
break;
} catch(NoMatchingViewException ex) {
// do nothing
}
}
final int uiElementId = testId;
onView(withId(uiElementId)).withFailureHandler(new FailureHandler() {
#Override
public void handle(Throwable error, Matcher<View> viewMatcher) {
onView(withId(uiElementId)).perform(scrollTo(), click());
}
}).perform(click());
As you can see I just catch the thrown NoMatchingViewException and do nothing with it until it finds the right id and break out of the for-loop.
My question is:
Is there a better approach which we can use to loop through it to see which id is displayed and if so click on it?
In my mind I came up with this idea, but it is not integrated in Espresso:
for(int id : uiElementIds) {
if(onView(withId(id)).exist()) {
performClick();
}
}
According to your question
My question is:
Is there a better approach which we can use to loop through it to see which id is displayed and if so click on it?
In my mind I came up with this idea, but it is not integrated in
Espresso:
for(int id : uiElementIds) {
if(onView(withId(id)).exist()) {
performClick();
}
}
Here's my old Espresso framework Activity tests:
#RunWith(AndroidJUnit4.class)
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DetailsActivityTest {
#Rule
public ActivityTestRule<MainActivity_> mRule = new ActivityTestRule<>(MainActivity_.class);
//TODO: Write tests to check if views are visible
private final int[] allDetailsActivityViewsIdis = {
R.id.dItem,
R.id.dDayAndDate,
R.id.dDay,
R.id.dDate,
R.id.dCity,
R.id.dTempAndIcon,
R.id.dTemperature,
R.id.dHighTemp,
R.id.dLowTemp,
R.id.dDescriptionLayout,
R.id.dDescription,
R.id.dForecast,
R.id.dHumidityLayout,
R.id.dHumidityDesc,
R.id.dHumidityVal,
R.id.dPressureLayout,
R.id.dPressureDesc,
R.id.dPressureVal,
R.id.dWindLayout,
R.id.dWindDesc,
R.id.dWindVal
};
private final int[] detailsActivityTextViewsIdis = {
R.id.dDay,
R.id.dDate,
R.id.dHighTemp,
R.id.dLowTemp,
R.id.dDescription,
R.id.dHumidityVal,
R.id.dPressureVal,
R.id.dWindVal,
};
private final int[] detailsActivityTextViewsDefaultValues = {
R.string.day,
R.string.date,
R.string.high_temp,
R.string.low_temp,
R.string.description,
R.string.humidity_val,
R.string.pressure_val,
R.string.wind_val,
};
#Before
//TODO: Rewrite this code using espresso-intents
public void checkIfAllDetailActivityViewsAreDisplayed() throws InterruptedException {
for (int viewId : allDetailsActivityViewsIdis)
onView(withId(viewId)).perform(click());
}
#Test
public void checkIfDetailsActivityViewsHaveNoDefaultValue() throws InterruptedException {
for (int viewId : detailsActivityTextViewsIdis)
for (int valueId : detailsActivityTextViewsDefaultValues)
onView(withId(viewId)).check(matches(not(withText(valueId))));
}
}
As you see, using foreach with Espresso is possible, but instead of exists() use check(matches(...) with value: isDisplayed, isDisplayedAtLeast or isCompletelyDisplayed
Hope it would help you

Button Text and Booleans (Simple Android App)

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);
}

How do I make "contains" in android to disregard the capitalization of a letter?

I'm trying to write a basic AI that responds back to text.
However, in this code ;
public void registermessage(View view) {
if (edittext.getText().toString().contains("hello")){
test.setText("Hello, sir.");
} else{
test.setText("It would be better off to say hello first, sir.");
}
Whenever I write Hello, it isn't registered as hello. I want to disable any filter for capitals in that edittext. How do I do that?
Thank you!
You can use java.util.regex.Pattern with the CASE_INSENSITIVE :-
Pattern.compile(Pattern.quote(your_text), Pattern.CASE_INSENSITIVE).matcher("hello").find();
or You can use this:-
org.apache.commons.lang3.StringUtils.containsIgnoreCase(your_text, "hello");
String tmp = edittext.getText().toString();
tmp = tmp.toUpperCase();
if (tmp.contains("HELLO")) {}
Use this instead :
public void registermessage(View view) {
if (edittext.getText().toString().toLowerCase().contains("hello")){
test.setText("Hello, sir.");
} else{
test.setText("It would be better off to say hello first, sir.");
}

Android: how to multiply values from EditText?

Ok, first thing is that I am new in Android development, please do not shoot me for the question.
So, I am developing an app yhat needs to multiply from 3 EditTexts:
resultsEditText
amountEditText
taxEditText
They are set with the same name in the R.java. what I want is the following:
amountEditText * taxEditText = resultsEditText
I have no idea in how to implement this, I have searched the internet and this site, which I use as a reference for all my Android development needs, and all the code I found doesnt work at all. I dont know what else to do. Thanks in advance!
You need to set EditText input type as number as well so user can input only numbers.
int a = Integer.parseInt(resultsEditText.getText().toString().toTrim());
int b = Integer.parseInt(amountEditText.getText().toString().toTrim());
int c = Integer.parseInt(taxEditText.getText().toString().toTrim());
int result = a * b * c;
Button btnCal,btnSub;
EditText editLen,editWid,editFeet;
int a,b,res;
btnSub=(Button)findViewById(R.id.btnSub);
btnCal=(Button)findViewById(R.id.btnCal);
editLen=(EditText)findViewById(R.id.editLen);
editWid=(EditText)findViewById(R.id.editWid);
editFeet=(EditText)findViewById(R.id.editFeet);
btnCal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(editLen.getText().toString());
b = Integer.parseInt(editWid.getText().toString());
res=a*b;
editFeet.setText(String.valueOf(res));
}
});

Categories

Resources