Getting decimal number from edittext - android

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>

Just do this:
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....
get the number decimal from edittext using this
Double BText=ParseDouble(String.valueOf(edittext.getText()));
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;
}

Related

Facing problem on changing TextView text on buttonclick

I have a button(button) and a textview(text) in my application. Before clicking on the button the textview text will always be "Start Search".But After clicking on the button , a function(scanning()) will be called. For executing the function it takes some times. So I want the texview text to be "Please wait" between the time after clicking the button and before getting the result of the function. And after getting the result of the function the textview text will be change to "Found" or "Not Found".
But problem is ,it never shows "please wait". After clicking on the button it shows "Start search" until getting the result of the function.
How to show "please wait" on the textview until it gets the result from the function after clicking on the button ??
Button button = (Button) findViewById(R.id.search);
TextView text = (TextView) findViewById(R.id.searchR);
text.setText("Start Search");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text.setText("Please Wait");
boolean res=scanning();
if(res==true)
text.setText("Found");
else text.setText("Not Found");
}
});
XML Part:
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="30dp"
android:text="Search"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/searchR"
android:layout_width="0dp"
android:layout_height="34dp"
android:layout_marginStart="97dp"
android:layout_marginLeft="97dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/search"
app:layout_constraintTop_toTopOf="parent" />
In the scanning part, I did some searching for BLE devices using UUID. If that device is found then I returned true otherwise false;
Introduce a small delay after you change the text to "Please Wait" and before calling scanning().
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text.setText("Please Wait");
Handler delayHandler = new Handler();
delayHandler.postDelayed(new Runnable() {
#Override
public void run() {
boolean res=scanning();
if(res) {
text.setText("Found");
}
else{
text.setText("Not Found");
}
}
},100);
}
});
Edit: Depending on your code, you may need to declare your variables as static or maybe global for this to work.
I found some mistakes in your code.
You are changing text of Button instead of TextView.
public void onClick(View v) {
text.setText("Please Wait");
boolean res=scanning();
if(res==true)
but1.setText("Found");
else but1.setText("Not Found");
}
Here
but1.setText
should be replaced with
text.setText
Your scanning method is returning result very fast, that's why you will not get Please Wait text.
Write external method for change text,
for example:
public void onClick(View v)
{
changeText("Please Wait");
boolean res = scanning();
if (res) // (res == true) is unnecessary, you can use like this
changeText("Found");
else changeText("Not Found");
}
private void changeText(string s)
{
text.setText(s);
}

Unable to check Edittext with inputType "phone" if null in Android

I am trying to check whether the user has enter his/her mobile number in the EditText on the button click event, but I am not able to check whether the EditText is empty or not when control comes to "editRegMobile". When I click on the button it doesn't show the message in the Toast. I also want to check the format of the mobile number i.e "+91 999999999" country code. I am able to check for other EditText but not for Mobile EditText.
xml code:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/editRegMobile"
android:layout_gravity="center_horizontal"
android:background="#drawable/sign_in_up_textbox"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="35dp"
android:textSize="16sp"
android:letterSpacing="0.08"
android:singleLine="true" />
Java code:
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editRegName != null && TextUtils.isEmpty(editRegName.getText().toString().trim())) {
editRegName.setError("Required!");
editRegName.requestFocus();
} else if (editRegEmail != null && TextUtils.isEmpty(editRegEmail.getText().toString())) {
editRegEmail.setError("Required!");
editRegEmail.requestFocus();
} else if (!(editRegEmail != null && TextUtils.isEmpty(editRegEmail.getText().toString()))) {
if (!Patterns.EMAIL_ADDRESS.matcher(editRegEmail.getText().toString()).matches()) {
editRegEmail.setError("Invalid Format!");
editRegEmail.requestFocus();
}
} else if ((editRegMobile != null) && TextUtils.isEmpty(editRegMobile.getText().toString())) {
Toast.makeText(getApplicationContext(), "Please enter mobile number!", Toast.LENGTH_SHORT).show();
} else if (!(editRegMobile != null && TextUtils.isEmpty(editRegMobile.getText().toString()))) {
if (!Patterns.PHONE.matcher(editRegMobile.getText().toString()).matches()) {
Toast.makeText(getApplicationContext(), "Please enter valid mobile number!", Toast.LENGTH_SHORT).show();
}
}
}
});
You can make
if(editRegMobile.getText().length() == 0)
Or
editRegMobile.getText().toString().length()
The second way cost some performance because need convert to String first
Simple to check for empty :
edittext.getText().toString().length() == 0

Android Button setText not being updated

I am writing code for an inbox-like activity which has a button that leads to the messages. This button has a text field that counts how many messages are in the inbox.
My problem is that the button's text field is not changing when the number of messages changes. It is not a problem of the app not checking for updates, and the code with setText is being called with the correct number to update.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("onCreate", "Main");
// Checking if there is login
if (ParseUser.getCurrentUser() == null) {
navigateToLogin();
} else {
// Setting pointers for buttons.
// onClick methods follow.
askButton = (Button) findViewById(R.id.buttonAsk);
ansButton = (Button) findViewById(R.id.buttonAnswer);
inboxButton = (Button) findViewById(R.id.buttonCenter);
mUser = ParseUser.getCurrentUser();
updateInbox();
}
This is the method that checks for new messages and updates the button.
private void updateInbox() {
Log.v(TAG, "Updating inbox");
ParseQuery responses = new ParseQuery(ParseConstants.CLASS_ANSWER);
responses.whereMatches(ParseConstants.KEY_SENDER_ID, mUser.getObjectId());
try {
responsesCount = responses.count();
Log.v("responses count" ,""+responsesCount);
if (responsesCount > 0) {
inboxButton.setText(String.valueOf(responsesCount));
}
Log.v("InboxActivity","Label set to " + responsesCount);
} catch (ParseException e) {
Log.v("InboxActivity", e.getMessage());
}
}
updateInbox gets called correctly and in the correct moments, so I only added its code to make this as clean as possible. Here is the xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context=".MainActivity"
android:clickable="false"
>
<Button
android:layout_width="80sp"
android:layout_height="80sp"
android:id="#+id/buttonCenter"
android:layout_gravity="center"
android:layout_centerInParent="true"
android:textSize="30sp"
android:text=""
android:textColor="#color/black_overlay"
android:background="#drawable/greenbutton"/>
EDIT:
Hi all, thanks for the help. I figured out the problem and posted it as an answer. It was a logical error, nothing to do with Android.
try this:
inboxButton.post(new Runnable(){
#Override
public void run(){
inboxButton.setText(String.valueOf(responsesCount));
}
});
(responsesCount should be final)
Try below code
import android.widget.RemoteViews;
if (responsesCount > 0) {
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout); //where my_layout is the layout file where the button resides.
remoteViews.setTextViewText(R.id.button, "Set button text here");// where button is id of the button.
}
findViewById doesn't exist for a widget.
Below code will work for you
runOnUiThread(new Runnable() {
#Override
public void run() {
if (responsesCount > 0) {
inboxButton.setText(String.valueOf(responsesCount));
}
}
});
You may use AsyncTask for smoothness of app flow.
I realized that the text was only getting updated when the number of responses was > 0. The button was updating correctly otherwise so I had to put an else statement to make sure the button always got updated. I edited the question with the correct answer in comments.
responsesCount = responses.count();
Log.v("responses count" ,""+responsesCount);
if (responsesCount > 0) {
inboxButton.setText(String.valueOf(responsesCount));
///////////////////////////////////
// MY EDIT HERE
//} else{
// inboxButton.setText("");
///////////////////////////////////

comparing two strings in Android ( if-else statemente)

I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?
The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}
please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}
try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}
Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}

Android - How to check if textview is null or not null

I have some textview in my application
and want to check whether the properties of text on my textview has a value or null.
then i want to display a toast if the value on my textview null
but the toast is not running as it should
this is my code :
public class brekeleV2 extends Activity {
static Context context;
brekeleV2Model r = new brekeleV2Model();
private EditText jalan, kota, postal;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
Button go = (Button)findViewById(R.id.go);
go.setOnClickListener(onGo);
Button reset = (Button)findViewById(R.id.reset);
reset.setOnClickListener(onRes);
jalan =(EditText)findViewById(R.id.jalan);
kota =(EditText)findViewById(R.id.kota);
postal =(EditText)findViewById(R.id.post);
jalan.setText(null);
kota.setText(null);
postal.setText(null);
}
and this is the onClick method code:
private View.OnClickListener onGo=new View.OnClickListener() {
public void onClick(View v) {
if (jalan.getText()!= null && kota.getText()!=null){
switch(v.getId()){
case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.brekele", "com.openit.brekele.brekeleV2Nav");
brekeleV2Nav.putLatLong(lat, lon);
startActivity(maps);
break;
}
}else{
Toast msg = Toast.makeText(brekeleV2.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
if(!textview.getText().toString.matches(""))
{
// not null not empty
}else {
//null or empty
}
This is what I would use.
if (mText1.getText().length() > 0 && mText2.getText().length() > 0) {
// Your code.
}
in the end i found my problem solving. here is my code:
if (jalan.getText().toString().length()>0 || kota.getText().toString().length()>0){
//switch(v.getId()){
//case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.razer", "com.openit.razer.mapRazerNav");
mapRazerNav.putLatLong(lat, lon);
startActivity(maps);
//break;
//}
}else{
Toast msg = Toast.makeText(razerNav.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
i used to check the length, because on my xml i add like this :
android:text=" "
see? this is my fault.
anyway thanks for helping me. :)
TextView has a public length() method you can use to check if there are any characters in the TextView.
if (textView.length() > 0) {
// textView is not null
} else {
// textView is null
}
Try textView.getText() != "" instead.
Are you sure that the else condition is invoked? Debug it!
Maybe you need to put the toast into a runOnUiThread statement:
runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
Method getText() in TextView returns EditAble that cant compare with String
you should convert EditAble to String using String.ValueOf() method.
String jalanContent = String.ValueOf(jalan.getText());
if(jalanContent.equals(""){
//do your action here
} else {
//some action here
}
hope it'd be usefull
if (jalan.getText()!= null && kota.getText()!=null)
This is the line of code that doesn't work for you.
Best solution for such scenario is using matches("") method for String
So the solution will be:
if (!jalan.getText().toString.matches("") && !kota.getText().toString().matches("")){
// code for not null textViews
}
else
{
//Code for nul textView
}
I would have modified the correct answer a bit (missing () after toString but we're not allowed edit code so:
if(textview.getText().toString().matches(""))
{
// is null or empty
}else {
//not null or empty
}

Categories

Resources