I am learning to develop on android on android studio and I encountered a problem.
I have multiple EditText controls for user info: First Name, Last Name, Address and I want them to behave the same when they are in focus and out of focus.
For example, my emailInput EditText control has "Email Address" as its text property. When the user clicks "Email Address" disappears and if the user didn't add any input and leaves the control "Email Address". This is what this method does:
private string emailAddress = "Email Address";
public void onFocusChange(View view, boolean focus)
{
(EditText) email = (EditText) findViewById(R.id.emailInput);
if(!focus && (email.getText()).equals(""))
{
email.setText(emailAddress);
}
else if(focus && (email.getText()).equals(emailAddress))
{
email.setText("");
}
}
I have like 20 controls and I don't want to copy and paste the same code and change the variables.
I have two questions: Can I get the id of the control that calls the onFocusChange method so the first line becomes ->
(EditText) ctrl = (EditText) findViewById(R.id.(this.getId());
and can I add a new property "Initial Text" to EditText controls so I can get something like this ->
if(!focus && (ctrl.getText()).equals(""))
{
ctrl.setText(ctrl.getInitialText());
}
else if(focus && (ctrl.getText()).equals(ctrl.getInitialText()))
{
ctrl.setText("");
}
EDIT: This is sort of like creating my own control that inherits from the EditText class. I'm just adding an object variable(Initial Text) and a method(getInitialText). Can I create my own control like this and still have the Drag and Drop feature in android studio?
Thanks! :D
The behaviour you describe is exactly what the android:hint attribute on any EditText does.
http://developer.android.com/reference/android/widget/TextView.html#attr_android:hint
Related
I am trying to add the text written in a textfield everytime and add it into an ArrayList. For eg- if the text "abcdef" is written in the textfield, then it should get added into the list. Again if the text "ghijkl" is written in the textfield, than that should get added.
My code for adding the text into the listview:
final ArrayList<String> mylist = new ArrayList<String>(5);
String s3=text1.getText().toString();
if(s3!=null)
g++;
else g--;
if(g>0) {
for(int i=0;i<mylist.size();i++) {
mylist.add(s3);
Toast.makeText(getApplicationContext(), mylist.get(i), Toast.LENGTH_LONG).show();
}
}
Is this the right way to do this? Also I am trying to get the list item for testing purpose, but I don't get any toast.
I assume you like to add the Content of your EditText field into the list after pressing a button, so you could do it like this:
// Member to store your Texts in list
private ArrayList<String> _list = new ArrayList<>()
// Method to call to add an entry to your list
// Either by pressing a button, removing focus of your edit text or something else
private void addTextToList()
{
String text = text1.getText().toString();
if (text != null)
{
_list.add(text);
}
}
private void showToast()
{
for(String text: _list)
{
Toast.makeText(this, mylist.get(i), Toast.LENGTH_LONG).show();
}
}
The toast is not shown because you need to pass your current activity.
Assuming your Code is in your activity, I passed this in the example above.
you have to make a button to handle this action every click i make editTex ,textView and Button
this is the action of button it every click take the value of editText and stor it in ArrayList and increse String by this value
public void getText(View v){
if(ed.getText().toString().length()!=0){
s+="\n"+ed.getText().toString();
arr.add(ed.getText().toString());
}
tv.setText(s);
}
I have an alertDialogue popup when a user wants to create a game, and it asks the user how many points they would like to gamble in the game, but it keeps throwing a null reference error and I am not too sure why.
This is my alertDialogue positive button click listener
alertDialog.setPositiveButton("Confirm Wager", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
createLobbyGame();
double wagerD;
String wager;
TextView wagerRV = findViewById(R.id.wagerRV);
wagerD = Double.parseDouble(edittext.getText().toString());
wager = Double.toString(wagerD);
boolean wage = wager.endsWith("0");
if(wage) {
wagerRV.setText(wager+"0");
} else {
wagerRV.setText(wager);
}
}
});
It throws an error when it tries to setText. This is the error it throws
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I know I had this working in the past, but I must have changed something to make it not work properly anymore but I have no idea what I would have changed.
I know this is a very common and simple problem, but I have looked at many other answers and have not found a solution that works for me.
Any help?
TextView declaration:
TextView wagerRV = (TextView) ((AlertDialog.Builder) alertDialog).findViewById(R.id.wagerRV);
How I am defining alertDialog:
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(FlipCoinLobby.this);
final EditText edittext = new EditText(FlipCoinLobby.this);
alertDialog.setView(edittext);
Your wagerRV is null because it can't find R.id.wagerRV.
You need to retrieve views from within onClick() using the dialog reference.
Change
TextView wagerRV = findViewById(R.id.wagerRV);
to
TextView wagerRV = (TextView) ((AlertDialog) alertDialog).findViewById(R.id.wagerRV);
Remove any unnecessary casting (I don't have IDE at the moment).
Update based on comments and question edit:-
alertDialog.setView(edittext) --> your alertDialog does not have any TextView with id R.id.wagerRV. Please check out some examples online on setting the content view with XML and that XML should have that TextView. If your wagerRV is in the activity and not inside the dialog, then declare it at the activity level, not inside onClick of alertDialog.
Update 2
You need to change your builder to the actual AlertDialog using AlertDialog alertDialog = alertDialogBuilder.create();. And then the casting will work too.
I am developing a android calculter and I want to add the number the user clicks when he clicks its button
i added the onclick like this
android:onClick="number(1)"
the number inside the brackets is the number that i want it to be appended inside the EditText
and the code of the main activity and the function is
public void number(int medo){
EditText result = (EditText) findViewById(R.id.result);
result.setText(result.getText() + " " + medo);
}
but when i click any button while testing the app it crashes so may anybody tell me how to fix this but fast please
Your method needs to have a View parameter, which will contain the button you clicked.
So, your code could look like this:
public void number(View v) {
EditText result = (EditText) findViewById(R.id.result);
// get the text from the button that was clicked and add it to the EditText
result.setText(result.getText() + " " + ((Button)v).getText().toString());
}
You can't set the argument in XML. It should look like this:
android:onClick="number"
Also i think you have to call toString.
result.getText().toString()
the onCLick should be a method that has a view parameter in it.
this View represents the View (in this case Button) was clicked.
you method should be like that:
public void number(View view)
to solve your problem i will suggest putting android:tag in the xml.
for the Button you showed you will do:
android:tag="1"
android:onClick="number"
and in the number function you will do something like that:
public void number(View view)
{
result.setText(result.getText() + " " + view.getTag().toString);
}
in addition, i will highly suggest to make result to a global variable and initialize it in the onCreate() instead, it will make the code better and efficient
I have an EditText field that represents an ID number. That field can either be filled programmatically, using IDField.setText(String) based on the results of a card swipe, or it can be filled manually using the keyboard.
Once the text is filled both methods (auto login--based on swipe, or manual--based on button click) both run the same sign in script. However when I go to grab the contents of the EditText field, if I edited the text manually I get an empty string returned. If the text was set programmatically then it works perfectly.
This doesn't make any sense to me. Is there a reason that editText.getText().toString() would not return the content that is visibly shown in the textbox?
XML:
<Button
android:id="#+id/btn_swipeCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/signInID"
android:layout_toLeftOf="#+id/textView1"
android:onClick="SignInStudent"
android:text="Swipe ID" />
Button Initialization:
IDField = (EditText) layout.findViewById (R.id.signInID);
LoginButton = (Button) findViewById(R.id.button1);
LoginButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { SignInStudent(); } } );
Card Swipe:
// displays data from card swiping
private Runnable doUpdateTVS = new Runnable()
{
public void run()
{
try
{
//Grab ID Number
String[] splitMSG = strMsrData.split("=");
//txtIDNumber.setText(splitMSG[2]);
IDField.setText(splitMSG[2]);
StringBuffer hexString = new StringBuffer();
hexString.append("<");
String fix = null;
for (int i = 0; i < msrData.length; i++) {
fix = Integer.toHexString(0xFF & msrData[i]);
if(fix.length()==1)
fix = "0"+fix;
hexString.append(fix);
if((i+1)%4==0&&i!=(msrData.length-1))
hexString.append(' ');
}
hexString.append(">");
myUniMagReader.WriteLogIntoFile(hexString.toString());
SignInStudent();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
Sign In Logic:
public void SignInStudent()
{
String temp = "http://wwww.tempUrl.com/signIn?ID="+ IDField.getText().toString() + "&DeviceId="+KEY;
webView.loadUrl(temp);
}
The layout is only updated during the onCreate phase of the loop. This is fired when an onResume event is called as well which explains why the fields update after you lock and unlock the device. There are a few workarounds for this such as doing more background processing and then creating a new view with correct values, or using a surfaceView that allows drawing to occur while the program is in its normal execute cycle.
For my application I either do background processing and then move to a new view, or have a view that just keeps calling itself to get the onCreate events to fire again. The solution depends on the application, but that's why the problem occurs.
In my app I have an edit user details page and I want to display the current name, email address etc in the corresponding editText fields and then the user can just erase that and enter a new one if they want.
Is there a way to do this? Thanks for any help
There is the hint feature? You can use the setHint() to set it, or set it in XML (though you probably don't want that, because the XML doesn't 'know' the name/adress of your user :) )
You can use EditText.setText(...) to set the current text of an EditText field.
Example:
yourEditText.setText(currentUserName);
From the xml:
android:text="yourtext"
You can use text property in your xml file for particular Edittext fields.
For example :
<EditText
android:id="#+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
You can do it in this way
private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "abc#xyz.com";
and inside onCreate method
nameEdit = (EditText) findViewById(R.id.name);
nameEdit.setText(nameDefaultValue);
nameEdit.setOnTouchListener( new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
return false;
}
});
nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
nameEdit.setText(nameDefaultValue);
} else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
}
});
emailEdit = (EditText)findViewById(R.id.email);
emailEdit.setText(emailDefaultValue);
emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
emailEdit.setText(emailDefaultValue);
} else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
emailEdit.setText("");
}
}
});
First you need to load the user details somehow
Then you need to find your EditText if you don't have it-
EditText et = (EditText)findViewById(R.id.youredittext);
after you've found your EditText, call
et.setText(theUserName);
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.et);
EditText et_city = (EditText) findViewById(R.id.et_city);
// Set the default text of second EditText widget
et_city.setText("USA");
}
}
Use android android:hint for set default value or android:text
We wish there is a default value attribute in each view of android views or group view in future versions of SDK. but to overcome that, simply before submission, check if the view is empty equal true, then assign a default value
example:
/* add 0 as default numeric value to a price field when skipped by a user,
in order to avoid parsing error of empty or improper format value. */
if (Objects.requireNonNull(edPrice.getText()).toString().trim().isEmpty())
edPrice.setText("0");