简体   繁体   中英

Getting decimal number from edittext

I know something similar has already been asked, but I'm having some trouble to get a decimal number that come from keyboard.

My Java code in the onCreate method should be:

textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v)
    {
        //how should I get here the number from keyboard?
        //I think  I should be something like
        //double S0=textS0.getText()....
    }
});

And that's what my XML file contains

<EditText
       android:id="@+id/editS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:ems="10"
       android:hint="@string/S0"
       android:inputType="numberDecimal" />
<Button
       android:id="@+id/getS0"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/setS0" />
</LinearLayout>

这样做:

double S0 = Double.parseDouble(textS0.getText().toString());
textS0=(EditText)findViewById(R.id.editS0);
Button btn_S0=(Button)findViewById(R.id.getS0);

btn_S0.setOnClickListener(new View.OnClickListener() 
{
public void onClick(View v)
{

           double S0 = Double.parseDouble(textS0.getText().toString());
}
});

May b you face null pointer exception in string so try this....

  1. get the number decimal from edittext using this

      Double BText=ParseDouble(String.valueOf(edittext.getText())); 
  2. after that paste this code.. it prevents you from null pointer exception

     double ParseDouble(String strNumber) { if (strNumber != null && strNumber.length() > 0) { try { return Double.parseDouble(strNumber); } catch(Exception e) { return -1; } } else return 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM