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

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!

Related

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

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.

How to make a button give different results everytime when user tap it?

I have a button and I want it to change the text that I positioned above the button to something random everytime the user press it. How can I do it?
I want to look something like this:
"Hello"
**press**
"Why did you press?"
**press**
"Don't do that again, or..."
**press**
"You just did!"
Here is the code of the button and the text.
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
textChange.setText(string.textChange2);
}
}
);
There is no magical way to have it randomly change the text, you have to program it to do that. You are going to have to create an array of responses and then in the button's code, tell it to cycle through those responses. So for example:
private String[] responseArray = {"Hello", "Why did you press?", "Don't do that Again", "You Just did!" }
private int numTimesPressed = 0
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
//note this line will cause an error if there is not enough values in the array. You would have to write a catch for this
textChange.setText(responseArray[numTimesPressed++]);
//if you want random, you'll have to change the array index you are accessing to random value between the array's bounds
}
}
);
You'll definitely need an array of string responses. Afterwards, the first approach I would use is to use a random number generator, and then just link it back to your array. Unfortunately I'm not able to write the code, since I don't know the exact syntax, but in pseudocode:
string array[x]={"Hello","Why did you press?",...};//Number of string responses (in this case it's 4)
int random_number;
random_number=RandomNumberGenerator(1,x);//1 and x are the lower and upper bounds
switch (random_number)://If you don't know, switch is basically a simplified if-else system
case 1:print "Hello";
.........
There are many random number generators online that you can use, depending on the language. Hope this helped!
P.S: Maybe you'll want to fine-tune your responses to make them more natural. For example, you probably want to re-roll your response if you get two of the same one in a row.

Cannot convert EditText text to int

I'm trying to make a simple golf scoring app and I have encountered a problem when I'm trying to convert the number thats in the EditText where the user enters the par for the hole. The user can only enter numbers into the EditText. It doesn't show any errors and doesn't crash when I run it but it is obviously not getting a value from this code below no matter what is in the EditText. If I set the par to a number other than 0 it will effect the total score when the user goes to the next hole so that part of the code is working. Also when I move this code to another method other than onClick(View v) the app crashes. All help is appreciated.
public void onClick(View v){
if (parNum.getText().toString().equals("")){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please enter the par");
alert.show();
}
else {
//editvalue is a string that I declared but gave no value.
editvalue = parNum.getText().toString();
par = Integer.parseInt(editvalue);
}
}
You are checking not equals "". So please Remove ! Symbol from your if condition.
if (parNum.getText().toString().equals("")){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please enter the par");
alert.show();
}
else {
//editvalue is a string that I declared but gave no value.
editvalue = parNum.getText().toString();
par = Integer.parseInt(editvalue);
}
I hope this will help you.

onClick method for programmatically created buttons

I've created an array of 5 clickable textviews using a loop, have set their parameters (size, colour, background image, to be clickable etc) and have set an onClickListener and the array is called "myArrayofTVs". Their ids have been set using the loop int (i). I have another predefined array that hold text string, and other textviews are present on the layout. Later on in the onClick method, and as all the buttons/clickable textviews do something very similar, I'd like to be able to do something like:
#Override
public void onClick(View v) {
if(v == myArrayofTVs[i]) { //using 'i' here doesn't seem to work
tv1.setText(myArray2[i]);
tv2.setText(myArray2[i+1];}
etc
etc}
I've tried various differnt ways such as using switch case statements (don't really want to use these as there will be a lot of repeated code and I'll have to add a new case statement each time I want to add new textview/buttons in the future). Is there anyway of using one statement that will handle all the buttons/clickable textviews based on the variable id given or will I have to use a separate case/tag/id statement for each one?
Many thanks in advance!
Add the views to your ViewGroup and use getChildAt(int index) and getChildCount() to create a loop. You can loop all children/views in the viewgroup and you could check with
if(child instanceof TextView)
if they are of the correct type. Then you could cast the views back to a TextView/Button/View and do the thing you want to do.
But it sounds like you want a list of something. So i would suggest using a ListView with a adapter behind it.
I really think you should use the id provided by Android instead of trying to compare objects. The reason your code wouldn't work, if it had a sufficient for loop around it, is somewhat mysterious, but I would try to parallel the switch statements you see in examples as much as possible by comparing ID's and not objects.
for( int i = 0; i < myArrayofTvs.length; i++ )
if(v.getId() == myArrayofTVs[i].getId()) {
tv1.setText(myArray2[i]);
tv2.setText(myArray2[i+1];
}
}
Also obviously you'll want to avoid an array out of bounds error in that second inner statement.
What I did was programmatically inflate my custom layout and used an onClickListener on that button from the custom layout inflated. Then to interact with a specific item I got the parent view of the view being clicked eg. your button and then used that view to change attributes of the view. This is a snippet of my code. The onClick of the alertDialog is where I go about changing values of the newly inflated view.
// if an edit button of numbers row is clicked that number will be edited
if (view.getId() == R.id.NumberRowEditButton)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Contact edit");
alert.setMessage("Edit Number");
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setSingleLine();
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// get input
Editable value = input.getText();
if(value.length() > 4){
View tempView = (View) view.getParent();
TextView tempTV = (TextView) tempView.findViewById(R.id.numberRowTextView);
String number = tempTV.getText().toString();
tempTV.setText(value.toString());
}
else
{
// ...warn user to make number longer
final Toast msgs = Toast.makeText(ContactEdit.this, "Number must be over 4 digits.", Toast.LENGTH_SHORT);
msgs.setGravity(Gravity.CENTER, msgs.getXOffset() / 2, msgs.getYOffset() / 2);
msgs.show();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// cancel the dialog
dialog.cancel();
}
});
alert.show();
}
Hopefully this might help you.

Make a custom keyboard in Android having the same behavior as the soft keyboard

So, today I decided to try out Android, so please understand that I am a beginner in it.
What I want to achieve right now is to have a EditText, and a set of buttons to be used to enter data into the EditText.
What I've done currently is stick a set of button widgets in the XML layout, and I use this code to make the buttons insert stuff into the EditText:
final EditText inputline = (EditText) findViewById(R.id.textentry);
final Button my_button = (Button) findViewById(R.id.my_btn);
my_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
inputline.append("a");
}
});
This kind of works, but I need help with a few issues:
it always appends the character at the end of the string, not at the current cursor position
similarly, when I call inputline.selectAll() and press my button, it inserts the text at the end of the string again; whereas I want it to delete the text first (as it's selected) and then insert the character
it seems tedious to write all that code for each of the buttons I have. Is there a better way to do this altogether?
Thanks for your help!
I have now pretty much solved by replacing inputline.append("a"); etc. with my custom function, lineInsert(), which you can see below.
public void lineInsert(CharSequence text) {
final EditText inputline = (EditText) findViewById(R.id.textentry);
int start = inputline.getSelectionStart();
int end = inputline.getSelectionEnd();
inputline.getText().replace(Math.min(start,end), Math.max(start,end), text, 0, text.length());
inputline.setSelection(inputline.getSelectionEnd());
}
This has the same behavior as the soft keyboard.

Categories

Resources