I am trying to assign a value fetched from my EditText to a double variable.
I have done something like this:-
public class PersonalInfo extends Activity implements OnClickListener
{
private double height=0.0d, weight=0.0d;
private CheckBox cbCheck;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_info);
try
{
height = Double.parseDouble(etHeight.getText().toString().trim());
weight = Double.parseDouble(etWeight.getText().toString().trim());
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
cbCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
Toast.makeText(PersonalInfo.this,height+weight), Toast.LENGTH_LONG).show();
}
}
});
}
}
}
When I debug the program, I get the value of Double.parseDouble(etHeight.getText().toString().trim()); perfectly. But somehow when I check the value of height and weight they remain null.
Thanks for any help,
You are getting text from editText early in onCreate. User interaction starts when activity resumes in onResume. So you need to get text from EditText when user has entered some value. Also you could do some checks
if(!TextUtils.isEmpty(etHeight.getText().toString())
{
// do something
}
So move the try catch block inside public void onClick(View v) {
Related
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.
image123(ImageView) works normal but when it comes to ONclickListener it does not work even after using different methods of Calling the listener.
I put func(),which contain findviewbyid of image123 (ImageView) just after SetContentView() and it works fine .OnclickListener of image123 does not works when func() is in OnClicklistener of Reset Button as Shown in the Code.
Problem:
How can i call the func() in reset button onclicklistener as well as in start at Oncreate() Activity?
It catch an exception shown in Log cat
- Exception at Onclick Listener" ,"java.lang.NullPointerException
public class MainActivity extends Activity {
ImageView image123;
int[] resultid=new int[25];
Button buttonExit;
Button buttonreset;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonreset=(Button) findViewById(R.id.button_reset);
buttonExit=(Button) findViewById(R.id.button_exit);
v1=(TextView)findViewById(R.id.name);
v2=(TextView)findViewById(R.id.fruit_count);
//--------------------------Exit Button---------------------------
buttonExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
//*******************Exception comes here*********************
try{
image123.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("Listner Called", "Listner Called");
}
});
}
catch(Exception e)
{
Log.d("Exception at onclickListener", e.toString());
}
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
func();
}});
}
void func()
{
String as=null;
int resultid;
SecureRandom random=new SecureRandom();
image123=new ImageView(this);
as=("img"+1).toString();
resultid=getResources().getIdentifier(as, "id","com.example.selectiongame" );
Log.d(as, ""+resultid);
image123=(ImageView) findViewById(resultid);
as="drawable"+(random.nextInt(3)+1);
resultid = getResources().getIdentifier(as, "drawable", "com.example.selectiongame");
Log.d(as, ""+resultid);
image123.setImageResource(resultid);
}
Try creating an array of ResIDs and an array of ImageViews. Then do something like this instead of initializing them with findViewById()...
for(int i = 0; i < res_arr.length; i++)
{
images[i] = new ImageView(this);
images[i].setImageResource(res_arr[i]);
images[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Button_Clicked", "Button Clicked");
}
});
}
You must not findviewbyid() of an ImageView in some other function other than Oncreate(Bundle b) or Some Listener(e.g OnclickListener ,onselectionchange etc) . if you want to findviewbyid(...) of a view in a function other than Oncreate ,Atleast Call that function once after SetContentView() and other prerequisite Findviewbyid(...).
2.
In order to Refresh your Activity ,when you can not use function containing findviewbyid(...) of ImageView,like in my case, in body some button(e.g Refresh ,Reset) OnclickListner .You must write the following code
buttonreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Bundle newBundle=new Bundle();
onCreate(newBundle);
//func(); >>We can not use this func() here if we are using it in Oncreate(...) in case of Array of ImageView
}});
}
For views other than Imageview ,Maybe Regular Line of Code work ...But in case of ImageView or Array of ImageView ....These things must be kept in mind and Simply Oncreate() must be used to Refresh.
i have 10 edittext values in activitya,i want to add them and show the result in newactivity.
my code
public class activitya extends Activity implements onclicklistener
{
private EditText editext1;
private EditText editext2;
private EditText editext3;
private EditText editext4;
private EditText editext5;
private Button calculate;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activitya);
calculate =(Button)findviewbyid(R.id.button1);
calculate.setonclicklistener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
onadd();
break;
default:
break;
}
}
public void onadd()
{
Bundle bundle = new Bundle();
String value1 = editext1.getText().toString();
String value2 =editext2.getText().toString();
bundle.putString("sendvalue1",value1));
bundle.putString("sendvalue2",value2));
try{
Double Total =Double.parseDouble(value1)+Double.parseDouble(value2);}
catch(NumberFormatException e)
{
e.printstacktrace();
}
bundle.putString("totalvalue",String.valueof(Total));
Intent a = new intent(this,newactivity.class);
a.putExtras(bundle);
startactivity(a);
}
}
in newactivity :
public class newactivity extends activity{
private TextView total;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
total =(TextView)findviewbyid(R.id.text1);
onview();
}
public void onview()
{
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("totalvalue");
total.setText(param1);
}
it shows the addition correctly only if i enter all the 10 values, strange
if i dont enter even one value it shows zero,
couldnt understand where the problem is
You have a try-catch and you do nothing in the catch. This is usually bad practice since you do not know when anything happens in your code.
In this case, Double.parseDouble is throwing an exception as you are trying to parse empty Strings. "" cannot be parsed to a double. "0" can.
You need to make sure that every edit text contains a valid value which can parse to a double or, test each value before trying to parse it.
To check all EditText length before you add all the values.
Like,
if(EditText1.getText.length()==0){
Toast.makeText(YourActivity.this,"All fields are mandatory ",
Toast.LENGTH_LONG).show();
}else if(EditText2.getText.length()==0){
} else if(){
..........
}else{
}
You will avoid NullPointerException
I have a custom view with 2 linear layouts: the first is the view's header and the second is the the details view.
In the custom view, the OnClickListener of the header Linearlayout is already defined: when it fires, it collapses/expandes the second linearlayout.
What I want to do is to add more functionalities to my header's OnClickListener event (i.e.: collapse/expand the second layout and show a Toast).
I can't modify the source code of the custom view. I tried to set a new OnClickListener but it hides the initial event (collapse/expand).
How should I implement this?
The source code of My Custom View:
public class ExpandoLayout extends ViewGroup
{
/* some declarations */
private Linearlayout header;
private linearlayout footer;
/* some code */
#override
protected void onFinishInflate() {
header= new LinearLayout(context);
header.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toggleExpand();
}
});
}
}
What I want to do is to add some code to the already defined OnClickListener event in my activity.
Something like that:
public class myActivity extends Activity {
private Linearlayout myCustomView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rsdetail);
myCustomView= (MyCustomView) findViewById(R.id.expanded);
myCustomView.getChildAt(0).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v instanceof LinearLayout)
{
v.performClick();
Toast.makeText(getActivity(), "ExpandoOnClickListener", 2000).show();
}
}
});
}
You can programmatically raise click event on a View to call it's OnClickListener as below:
view.performClick();
Now if you call this on your second layout under first layout's OnClickListener then i hope it should do the magic
Simple solution would be to get original OnClickListener and then fire it in new one:
final OnClickListener preDefinedListener = myCustomView.getChildAt(0).getOnClickListner();
myCustomView.getChildAt(0).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v instanceof LinearLayout)
{
preDefinedListener.onClick(v); // calls default (defined by MyCustomView)
Toast.makeText(getActivity(), "ExpandoOnClickListener", 2000).show();
}
}
});
Sadly, View does not have getOnClickListner(), but I guess you can use reflection to get it. It is stored in the field mOnClickListener (source).
This is how you can get OnClickListener defined for your layout:
OnClickListener tmpOnClickListener = null;
try {
Class<View> cls = (Class<View>) Class.forName("android.view.View");
Field fld = cls.getDeclaredField("mOnClickListener");
fld.setAccessible(true); // because it is protected
tmpOnClickListener = (OnClickListener) fld.get(myCustomView.getChildAt(0));
fld.setAccessible(false); // restore it's original property
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
final OnClickListener preDefinedListener = tmpOnClickListener;
if (preDefinedListener != null) {
myCustomView.getChildAt(0).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View paramView) {
preDefinedListener.onClick(paramView);
Toast.makeText(getActivity(), "ExpandoOnClickListener", Toast.LENGTH_LONG).show();
}
});
I didn't really bother to handle all exception correctly, but it's enough to get the idea.
It might look messy, but it's actually just 5 lines of new code to solve your problem.
Since SDK 15 you can just call method:
view.callOnClick()
If you cannot modify the code of CustomView then you have the below option.
Extend the CustomView.
Override the onClick() method and bind this as a Listener to the first layout.
Inside onClick() first call super.onClick() then add your additional functionality below.
This way you are keeping the existing code and adding additional functionality as well.
Can anyone please tell why the if statement never gets executed even though I enter ran in the edit text field and press ok? When the user enters ran and presses the button ok, I want another button to become visible which enables him to stop the current activity. Basically I want to know why the if is skipped.
public class Reciever extends Activity{
protected static final String TAG = null;
private Button ok,stp;
private TextView tv;
private EditText ev;
private String s1,s2,s3,s4;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
s1="nar";
setContentView(R.layout.stop);
tv=(TextView) findViewById(R.id.textView1);
tv.setText(s1);
ev=(EditText) findViewById(R.id.editText1);
ok=(Button) findViewById(R.id.ok_button);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
s2="ran";
tv.setText(ev.getText().toString());
s3=ev.getText().toString();
if(s3==s2)//not going inside this loop
{
stp=(Button) findViewById(R.id.stopb);
stp.setVisibility(View.VISIBLE);
stp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
});
}
}
if(s3==s2)//no
just replace the above line with below
if(s3.equalsIgnoreCase(s2))//no
Use .equals instead of == to compare the value of two strings.
if (s2.equals(s3))
Using == tests for reference equality. Two strings can contain the same characters but have different references.
You can't compare text with ==, you need to use equals.
if(s3.equals(s2))