How to save string written in EditText to string - android studio - android

I'm developing an application that allows user to add his own word, it's category. I start with a spinner that has the words available before in sqlite db and Add new word. When he clicks on Add new word, the spinner changes into EditText box that allows him to enter a new word. Whenever I try to save the text written in Edittext to string it shows that string is defined as "Add new word" and not the value entered by the user. What should I do?
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getId()==R.id.spinword)
{
editword=parent.getItemAtPosition(position).toString();
if(editword.equals("Add new word"))
{
spinwrd.setVisibility(spinwrd.INVISIBLE);
edtwrd.setVisibility(edtwrd.VISIBLE);
flag = 1;
}
if(flag == 1)
{
editword.replace(editword,edtcat.getText().toString());
}
}
if(parent.getId() == R.id.spincat) {
editcategory = parent.getItemAtPosition(position).toString();
if (editcategory.equals("Add new category")) {
spincat.setVisibility(spincat.INVISIBLE);
edtcat.setVisibility(edtcat.VISIBLE);
editcategory = edtcat.getText().toString();
}
}
}
I tried equals method and replace method but in vain.

Not sure of what you want to do but i think you should try changing
editword.replace(editword,edtcat.getText().toString()
for
editword.replace(editword,edtwrd.getText().toString())

The answer to this question is as follows: First, replacing, clearing, or any change depends on the position of the line meaning that: In the code above, I was trying to capture the text written by the user but at that point of execution when user chooses "Add new word" the text becomes it. The solution to this problem is to place the line of code editword.replace(editword,edtcat.getText().toString()); when this function is finished to be sure that the user has entered some text.

Related

TextUtils.isEmpty(regUserOtherCity.getText().toString()) doesnt work on button press

I have a spinner of cities with default value "Other City". If the user can't find his city, when he selects Other City, a textInput (Your city) is shown.
When the user enters his city name there and Clicks the button Register, the getText().toString() doesn't return the value. And also when the field is empty even though I have written validation code, it doesn't work.
Log.i("cities[0]", "("+cities[0]+")");
Log.i("regOtherCity", "("+(regUserOtherCity.getText().toString())+")");
if (userCity.equals(cities[0]) && TextUtils.isEmpty(regUserOtherCity.getText().toString()) )
{
error = true;
Log.i("checkerror", "("+cities[0]+")");
regUserOtherCity.setError("Enter Your City");
regUserOtherCity.requestFocus();
}
else if (userCity.equals(cities[0]))
userCity = regUserOtherCity.getText().toString();
Log.i("cities[0]", "("+cities[0]+")");
Log.i("regOtherCity", "("+userCity+")");
I have tried debugging by using Logcat, the output is here for the time when the user enters 'my city' in the text input.
I/cities[0]: (Other City)
I/regOtherCity: (my city)
I/cities[0]: (Other City)
I/regOtherCity: ()
Edited:-----------------------------
On inspection, I found out that the value returned by userCity is empty.
here is the code that gets value of userCity..for some reasons it's not working.
regCitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (String.valueOf(parent.getItemAtPosition(position)).equals(cities[0])) {
regOtherCityLayout.setVisibility(View.VISIBLE);
userCity = regUserOtherCity.getText().toString();
Log.i("onItemSel userCity", "("+userCity+")");
} else {
regOtherCityLayout.setVisibility(View.GONE);
userCity = String.valueOf(parent.getItemAtPosition(position));
}
}
You're assigning userCity the value of the EditText inside onItemSelected. So if the user select Other City, the EditText value is assigned to userCity in the listener instead of the value of the EditText.
Simply assign the spinner value and use the if condition to set the visibility of the EditText.
userCity = String.valueOf(parent.getItemAtPosition(position));
Should work fine when you press the button then.

Select item from AutoCompleteTextView in uiautomator

UPDATE
This project is no longer maintained today, but solutions are most welcomed.
Thanks.
I am creating an automation test project in which I have issue to select the item from the AutoCompleteTextView.
You can see the snap and the views[all expanded] it has. The dropdown of the AutoCompleteTextView does not appear in view tree nor I am able to select using mouse.
I have tried below approaches to select the item form from the AutoCompleteTextView adapter:
UiScrollable locationList = new UiScrollable(new UiSelector().scrollable(true)); locationList.scrollTextIntoView(location);
UiScrollable locationList = new UiScrollable(locationEditText.getSelector()); locationList.scrollTextIntoView(location); Here locationEditText is my AutoCompleteTextView
UiObject selectedLocation = locationList.getChild(new UiSelector().text(location)); selectedLocation.click(); from the locationList it does not select the item with the string passed.
editLocationResId = "android:id/text1"; UiObject selectedLocation = new UiObject(new UiSelector().resourceId(editLocationResId)); selectedLocation.click(); The id from the adpter textview does not work either.
Can anybody help me with selecting the item from the AutoCompleteTextView in uiautomator? Or the more approaches get the desire output.
Get the cordinates of text field :
int x = element.getLocation().getX();
int y = elmement.getLocation().getY();
Add values to get the right cordinates.
x = x+x1
y = y+y1
Use tap function to click on it.
TouchAction action = new TouchAction(driver);
action.tap(x,y).perform();
first open the pick-up list, then try to use UiDevice.pressKey(), to send a DPAD_DOWN OR UP event and press Enter to select the item you want.
If you need to press the first element from the dropdown list, I have found a useful workaround:
public void selectFirstElement() {
TouchAction touchAction = new TouchAction(getAppiumDriver());
int xTapped = autoCompleteTextView.getLocation().getX() + autoCompleteTextView.getSize().getWidth() / 2;
int yTapped = autoCompleteTextView.getLocation().getY() + autoCompleteTextView.getSize().getHeight() ;
touchAction.tap(xTapped, yTapped).perform(); }
Given an AutoCompleteTextView declared as autoCompleteTextView, you can get the current location on the screen and calculate the item which is gonna be located below it. Hope it helps!
Well, i found a turn around(this is for autocompletetextview, for spinner delete setText()):
UiObject edit = mDevice.findObject(new UiSelector().className(EditText.class).instance(0));
edit.click();
edit.setText(name);
Rect rect = edit.getBounds();
mDevice.waitForWindowUpdate(Package.DIGI_PACKAGE, 1000);
mDevice.click(rect.left + 64, rect.bottom + 72);
Get object, click it, insert text that you want,wait for dropdown to appear then click under it with some pixels
I had created and have been using the simplest and the most efficient way. Just locate, type and then select the desired value in autocomplete text view.
Hope it will work for you as well.
driver.findElement(By.id(“Element ID”)).clear();
driver.findElement(By.id(“Element ID”)).sendKeys("Type what you want to select");
driver.pressKeyCode(AndroidKeyCode.KEYCODE_PAGE_DOWN);
driver.pressKeyCode(AndroidKeyCode.ENTER);
You can find the element that you want to select using its text. Make sure that this line of code is executed after the suggestion list has been shown.
//Get a reference to the autocomplete element
UiObject2 autocomplete = device.findObject(By.res("yourpackage","autocomplete_id"));
//Put a text that will trigger the suggestion list
autocomplete.setText("68623 Lampertheim");
//Gain the focus
autocomplete.click();
//Finally, find the element that we want in the suggestion list and click it
device.findObject(By.text("68623 Lampertheim")).click();
Hope it helps.
try the code below it worked for me.
I am using the the AutoCompleteText to auto complete the location where the user is currently in, the locationList is nothing but an array that i wrote in the strings.xml file, so use your own string array here.
locationList = res.getStringArray(R.array.ticketLocation);
ArrayAdapter<String> locationAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, locationList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtCountries);
textView.setThreshold(1);
textView.setAdapter(locationAdapter);
textView.setValidator(new Validator());
textView.setOnFocusChangeListener(new FocusListener());
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView ticketLocation = (TextView) view;
getTicketLocation = ticketLocation.getText().toString();
}
});
and below is the code for validating the text input in the location field, the fixText() method prevent the user from typing text that does not exist in your string array, for instance: if the user type "germany" which does not exist in your string array list, it will be replaced by " " which is an empty string inside your edittext input field
class Validator implements AutoCompleteTextView.Validator {
#Override
public boolean isValid(CharSequence text) {
// Log.v("Test", "Checking if valid: " + text);
Arrays.sort(locationList);
if (Arrays.binarySearch(locationList, text.toString()) > 0) {
return true;
}
return false;
}
#Override
public CharSequence fixText(CharSequence invalidText) {
// Log.v("Test", "Returning fixed text");
/*
* I'm just returning an empty string here, so the field will be
* blanked, but you could put any kind of action here, like popping
* up a dialog?
*
* Whatever value you return here must be in the list of valid
* words.
*/
return "";
}
}
class FocusListener implements View.OnFocusChangeListener {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.v("Test", "Focus changed");
if (v.getId() == R.id.txtCountries && !hasFocus) {
// Log.v("Test", "Performing validation");
((AutoCompleteTextView) v).performValidation();
}
}
}

swithcing to next textview

Ok im making app and it have 15 button's and 6 textview's.I want when I press first button to change value of first textview(value is "") to something (number one for example).But problem is when i press second button if first textview is already set to some value to set set second textview to second value.
If you need something else ask in comments (sorry for bad English)
here is what I was doing(this is under onclick)when i press second button
if(textview1.equals("1")){
textview2.setText("2");}
else if (textview1.equals("")){
textview1.setText("2");
}
It sounds like you wish to show last 6 buttons pressed.
Store all pressed buttons in a List (i.e. LinkedList) of size 6. Initially, it will be empty.
Then whenever any button is pressed do two things:
1) add it to the List and delete old elements if size exceeds six.
2) set button values from List.
Second step can be achieved like this:
// all TextViews should be in a list
private List<TextView> textViews;
// declare as field
private List<String> memoryQueue = new ArrayList<String>();
public void update() {
//set fields for the pressed buttons
for (int i=0; i<6 && i<memoryQueue.size(); i++) {
String text = memoryQueue.get(i);
textViews.get(i).setText(text);
}
// set empty fields
for (int i = memoryQueue.size(); i<6; i++) {
textViews.get(i).setText("");
}
}
This code snippet assumes that you store your TextViews in a List.
And Easiest way to keep track of last six button:
public void buttonPressed(Button button) {
//get text based on your button
String text = button.getText();
if (memoryQueue.contains(text)) {
return;
}
memoryQueue.add(text);
if (memoryQueue.size() > 6) {
memoryQueue.remove(0);
}
}
Since you're concerned with the text inside of your text view, you should be using the object's getText method:
if( textview1.getText().equals("1") ){ // Edited
textview2.setText("2");
} else if (textview1.getText().equals("")){ //Edited
textview1.setText("2");
}
At first, you have to get the String text from TextView using getText() method then you can compare that String with another String. Now, change your condition as follows...
if(textview1.getText().toString().equals("1")){
textview2.setText("2");}
else if (textview1.getText().toString().equals("")){
textview1.setText("2");
}

EditText.setText() not working & getting wrong values from EditText

I'm a starter on Android, mocking a contact list of a phone. Now I have a contact list, like the pic below, when I press the one item of the contact list, it pops up a dialog with two choices. And if I choose "Add to Black", another AlertDialog allows me to put this number to the blacklist. What I want to realize here is to automatically read the number of the item I picked, show it in the "number" blank, which doesn't require users to input again. But it turned out it didn't work, still nothing in the blank. The screenshots and codes of showing the add-black-dialog are below.
final View view = getLayoutInflater().inflate(R.layout.add_person, null);
AlertDialog alertDialog = new AlertDialog.Builder(MyTabHost.this).setTitle("Add a Black Number")
.setView(view).setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(dataList.get(arg2).get("number"));
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
map.put("display", Utils.formatPhoneNumber(number));
if (MyTabHost.blackList.get(0).containsValue("You don't have any black number")) {
MyTabHost.blackList.removeAll(MyTabHost.blackList);
}
MyTabHost.blackList.add(map);
int i = mySharedPreference.getBlackSize() + 1;
mySharedPreference.saveBlack(remark, number, i);
mySharedPreference.saveBlackSize(i);
dialog.dismiss();
new AlertDialog.Builder(MyTabHost.this)
.setMessage("Black number succesfully added")
.setPositiveButton("OK", null).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
alertDialog.show();
Actually I'm thinking whether I am using wrong view. As the codes state above, I use final View view = getLayoutInflater().inflate(R.layout.add_person, null);to get the new view of the dialog, which add_person.xml here is my layout.
The reason why I wondering about the wrong view is that something weirder happened: when I manually inputed the number and remark(say I pressed the contact "Jack"'s number:8871203459 and "Jack" as a remark) and pressed "Add", meanwhile the things in the blanks suddenly change to some numbers else(some numbers I got in other activities), like below, and the black data stored was also the odd wrong number.
That's odd because I did write the codes of getText(), and saved it:
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(dataList.get(arg2).get("number"));
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
map.put("display", Utils.formatPhoneNumber(number));
This is a long and boring problem. Thanks for your reading and help...
Just moved relevant comment down into an answer.
That setText is only being run once you click the add button on your dialog. Move both find views and the setText out of the dialogs on click
use toString() Method for converting text into string and then place it in appropriate place. I faced a same problem and solved by this method.
I solved my second problem in this post. It was a careless mistaken by querying wrong ArrayList. This time the odd numbers don't exist. But the EditText is still not able to show the characters with what I want. Pls help if possible.
Update: I've found that though the EditView is not able to set the values visible to the users, it does get the value - I've tested that. What's odd is, whatever I input in the two blanks(should have shown the values) and press "Add" button, the app will always save the original value I try to let them show.
Specifically:
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(contactList.get(arg2).get("number").toString());
inputRemark.setText(contactList.get(arg2).get("name").toString());
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
My EditTexts are able to get the contactList.get(arg2).get("number").toString() and contactList.get(arg2).get("name").toString(), but just don't show them. And whatever else I input on the EditTexts, they will pass the two values above, instead of what I newly input, though I've specified String number = inputNumber.getText().toString() and String remark = inputRemark.getText().toString().
Finally update: Problem solved, it's not a hard tech one but a programming logical mistake. Please refer to #ElefantPhace's answer on the upper side if any one encounters same problem. Thanks all!

Mono for Android: Spinner ItemSelected event triggers on load but shouldn't?

I have a spinner with a few values and I fill it from my webservice.
Filling the spinner
int i = 0;
var dropItems = new List<SpinItem2>();
DataRow[] result = myOPTvalues.Tables[0].Select("FieldValue=" + item.FieldValue);
foreach (DataRow row in result)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals(""))
optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals(""))
optItem.FieldTextValue = null;
dropItems.Add(new SpinItem2(i, optItem.FieldValue.ToString(), optItem.FieldTextValue.ToString()));
}
i = 1;
foreach (DataRow row in myOPTvalues.Tables[0].Rows)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals(""))
optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals(""))
optItem.FieldTextValue = null;
if (optItem.FieldValue != item.FieldValue)
{
dropItems.Add(new SpinItem2(i, optItem.FieldValue.ToString(), optItem.FieldTextValue.ToString()));
}
++i;
}
For some reason it acts like the item that was inserted first is "selected" on default and then triggers the ItemSelected event which I use to send the selected but I don't want that.
Since there's quite a number of these spinners on my screen it really slows down the activity plus it also sends the incorrect values to the field and since I use the ItemSelect to detect if everything went OK (let's say the service fell or the values themselves changed on server (someone added a new field on the server application) while the user is completing the form etc.)
Is there someway to tell the app not to trigger that on activity load but on actual user interaction?
I can't speak for Android specifically, but I have encountered this many times with Windows.
The solution I usually use is to simply add a boolean loading variable. Set it to true at the beginning of your initialisation and then clear it at the end.
In your event handlers like ItemSelected you can simply check if this is being triggered as the result of the initial load.
private void onItemSelected(....)
{
if(loading)
{
return; //Ignore as form is still loading
}
//Normal event handling logic goes here
....
}
Before I declared GetView:
int LastSpinnerSelectedPosition;
Inside my spinner definition:
LastSpinnerSelectedPosition = 0;
My spinner ItemSelected event:
var CurrentSelectedIndex = SpinnerValue.SelectedItemPosition;
if (CurrentSelectedIndex != LastSpinnerSelectedPosition)
{
// WHATEVER I WANTED TO DO ON ITEM SELECT ANYWAY
// Fix the LastSpinnerSelectedPosition ;)
LastSpinnerSelectedPosition = CurrentSelectedIndex;
}
Simple ;D
Just for clarification, the event fires when an item is selected. The semantics are obviously flawed, but technically the item IS selected when it initially loads since you can then immediately ask the spinner for which item is selected, so as the other answers say, just ignore the first time it is selected since it's guaranteed to be the loading select, and then proceed as normal after that.

Categories

Resources