can i know pls why the input variable why it's giving me error always, thank you so much.
This is my code below:
public class MainActivity extends AppCompatActivity {
public TextView textView;
public EditText editText;
public Button btn;
public int input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
editText = findViewById(R.id.editText);
btn = findViewById(R.id.btn);
` input= Integer.parseInt(editText.getText().toString());`
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(input );
}
});
}
}
The error is happening as the String cant be cast to an integer. This could be because your editText is empty or that you have characters that are not integers in there (E.g. Letters). Therefor you should use try and catch to catch the error.
Currently you are trying to parse the input string from editText in onCreate() as soon as the view is created. This will try to parse the default text associated with the editText. I think what you want is to parse the input at the time of clicking button. In that case move the input parsing code inside onClick(). Also it is better to catch NumberFormatException when calling parseInt() if you cannot guarantee that the text entered in the EditText is always an integer.
#Override
public void onClick(View v) {
android.util.Log.i("MyActivity", "onClick: edit text = " + editText.getText());
input= Integer.parseInt(editText.getText().toString());
textView.setText(input );
}
I want to pass an edit text reference to onClickListener of a button, I have different options:-
I can pass it by creating a custom class and implementing onClickListener as given below:-
public class MyLovelyOnClickListener implements OnClickListener
{
EditText myLovelyEditText;
public MyLovelyOnClickListener(EditText myLovelyVariable) {
this.myLovelyVariable = myLovelyVariable;
}
#Override
public void onClick(View v)
{
String editTextValue = myLovelyEditText.getText().toString();
}
};
MyLovelyOnClickListener onClickListenerVar = new MyLovelyOnClickListener(myEditText);
ButtonVar.setOnClickListener(onClickListenerVar);
My intuition says the former is the correct method.
But I can also make the EditText a member variable and reference it from inside of the onClickListener. What is the problem with doing so if any?
ButtonVar.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
String editTextValue = mEditText.getText().toString();
}
});
Does the first method have any advantage compared to the second method?If yes, then what?
Just make the field in your Activity (or Fragment) and use that reference.
private EditText editText;
in OnCreate
editText = (EditText)findViewById(R.id.your_id);
in your onClickListener you can use:
editText.getText()
I have two date fields (no, not the pickers) as fromDate and toDate. When I click on my Submit button, in the onResume(), I have validations in place for both date fields. When I enter an invalid value (not from syntax, locale, etc. point of view) for toDate and click Submit, I correctly see the toast. Then, I enter the correct the value and click Submit. The toast still appears ! In other words, the corrected date value is not being received.
I guess, I am missing the activity life-cycle w.r.t. toasts. (Each Toast is immediately followed by a return.) Can you please suggest what should be the correct flow to handle this error followed by correction ?
public class MainActivity extends Activity {
private Locale l ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set locale;
l = getResources().getConfiguration().locale;
}
#Override
protected void onResume() {
super.onResume();
addButtonListener();
}
private void addButtonListener() {
Button submitButton = (Button) findViewById(R.id.buttonSubmit);
submitButton.setOnClickListener(new OnClickListener() {
EditText fromDateText = (EditText) findViewById(R.id.fromDate);
EditText toDateText = (EditText) findViewById(R.id.toDate);
#Override
public void onClick(View v) {
String s;
if (fromDateText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.err_fromDate_1, Toast.LENGTH_SHORT).show();
return;
}
if (toDateText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.err_toDate_1, Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
Edited to add source code.
Make fromDateText and toDateText class variables and init them in onCreate.
Here is my code. It just involves 2 buttons and a number counter that goes up and down as the buttons are pressed (both in integer value and text size). This activity is part of a larger application that follows the process:
1. splash screen
2. list menu
3. activity selected in menu (there are 3 options and the counter is one of them)
When i press the back button, it goes back to the list menu and when i click on the integer counter option, i want it to be restored exactly how it was
Any ideas on how i can do this?
Thanks!
public class StartingPoint extends Activity {
/** Called when the activity is first created. */
int counter;
Button add;
Button sub;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter=0;
add= (Button) findViewById(R.id.bAdd);
sub= (Button) findViewById(R.id.bSub);
display= (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText(""+counter);
display.setTextSize(counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText(""+counter);
display.setTextSize(counter);
}
});
}
}
You have two good options:
Either use SharedPreferences to store your variable onStop() and load it onStart() - How to use SharedPreferences in Android to store, fetch and edit values;
or, if it is just an integer, you can use the startActivityForResult method to instantiate your integer counter activity and capture the result from the activity, as explained in Android: Capturing the return of an activity.
Hope it helps!
This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Android setOnClickListener method - How does it work?
(5 answers)
Closed 1 year ago.
I'm trying to set and onclicklistener so that when I click within the edittext element it will clear its current contents. Is there something wrong here? When I compile this code I get a force quit and ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined error.
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText = (EditText)findViewById(R.id.editText1);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText.setOnClickListener(this);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText("");
}
}
Also you can use code below
editText.getText().clear();
First you need to call setContentView(R.layout.main) then all other initialization.
Please try below Code.
public class Trackfolio extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
editText.getText().clear(); //or you can use editText.setText("");
}
}
just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.
We can clear EditText data in two ways
First One setting EditText is empty like below line
editext.setText("");
Second one clearing EditText data like this
editText.getText().clear();
I suggest second way
Your code should be:
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == editText) {
editText.setText("");
}
}
}
For Kotlin:
Create two extensions, one for EditText and one for TextView
EditText:
fun EditText.clear() { text.clear() }
TextView:
fun TextView.clear() { text = "" }
and use it like
myEditText.clear()
myTextView.clear()
public EditText editField;
public Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_layout);
this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
editField.setText("");
}
}
Very Simple to clear editText values.when u click button then only follow 1 line code.
Inside button or anywhere u want.Only use this
editText.setText("");
package com.example.sampleproject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class SampleProject extends Activity {
EditText mSearchpeople;
Button mCancel , msearchclose;
ImageView mprofile, mContact, mcalender, mConnection, mGroup , mFollowup , msetting , mAddacard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
mSearchpeople = (EditText)findViewById(R.id.editText1);
mCancel = (Button)findViewById(R.id.button2);
msearchclose = (Button)findViewById(R.id.button1);
mprofile = (ImageView)findViewById(R.id.imageView1);
mContact = (ImageView)findViewById(R.id.imageView2);
mcalender = (ImageView)findViewById(R.id.imageView3);
mConnection = (ImageView)findViewById(R.id.imageView4);
mGroup = (ImageView)findViewById(R.id.imageView5);
mFollowup = (ImageView)findViewById(R.id.imageView6);
msetting = (ImageView)findViewById(R.id.imageView7);
mAddacard = (ImageView)findViewById(R.id.imageView8);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSearchpeople.clearFocus();
}
});
}
}
i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me
txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
txtDeck.setText("");
}
});
This works for me,
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
final EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
//Log.d("NNN", "Has focus " + hasFocus);
if (hasFocus) {
Toast.makeText(ctx.getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ctx.getApplicationContext(),
"loss the focus", Toast.LENGTH_SHORT).show();
}
return;
});
by setting Empty string you can clear your edittext
editext.setText("");
If the use of EditText is not mandatory, you can implement this behavior easily with the new material components:
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_field"
app:endIconDrawable="#drawable/ic_close_black_24dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_value"
android:maxLines="1"
android:text="#{itemModel.value}" />
</com.google.android.material.textfield.TextInputLayout>
You only have to specify the drawable you want for the button that will clear the text and the action that it will execute. To clear the text, you can use iconMode="clear_text", but also "password_toggle" is available.
In XML you can write like:
<EditText
android:id="#+id/txtsearch"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="1"
android:background="#drawable/roundlayoutbutton1"
android:ems="10"
android:gravity="center"
android:inputType="text"
android:textAllCaps="true"
android:text="search_xxxx"
android:textColor="#color/colorPrimaryDark"
android:visibility="visible" />
and in java class you may have below one :
EditText searchHost;
OnCreate() you write:
searchHost=findViewById(R.id.txtsearch);
searchHost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(searchHost.getText().toString().equalsIgnoreCase("search_xxxx")){
searchHost.setText("");
Toast.makeText(getApplicationContext(),"Enter you text xxx...", Toast.LENGTH_LONG).show();
}
}
});
It works fine for me.
You can use the 'android:hint' attribute in your EditText also from code:
editText.setHint(CharSequence hint / int resid);
Then you don't need any onClickListener or similar. But consider that the hint value won't be passed. The editText will be stayed empty. In this case you can set your editText with your deflault value:
if(editText.getText().toString().equals("")) {
...use your default value instead of the editText... }
It's simple: declare the widget variables (editText, textView, button etc.) in class but initialize it in onCreate after setContentView.
The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView.
And when you initialize the widget variable via findViewById you are accessing the id of the widget in the main layout in the setContentView.
I hope you get it!
I am not sure if your searching for this one
{
<EditText
.
.
android:hint="Please enter your name here">
}