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

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
}

Related

How to Check the empty text fields before uploading image or video in android?

I'm new to stackoverflow and android, sorry if i'm wrong. I am trying to check the text fields is empty or not, when the text field is empty, upload button should show please enter title and when user enters the text then only it should upload the image. After entering title then also it again shows the toast.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title1.matches("")){
Toast.makeText(getApplicationContext(), "Please enter the Title and Category", Toast.LENGTH_SHORT).show();
} else if(description1.matches("")){
Toast.makeText(getApplicationContext(), "Please Select Category", Toast.LENGTH_SHORT).show();
} else {
flag = 1;
// uploading the file to server
new UploadFileToServer().execute();
}
}
});
Any help would be appreciated.
To check for empty fields, use
if(TextUtils.isEmpty(editText.getText().toString())) {
// do something
}
or if you want to check if string is empty or null use -
if(TextUtils.isEmpty(stringToCheck) {
// do something
}
try this.
Place this code in your button onClickListener:
String mText = mEditText.getText().toString();
if(TextUtils.isEmpty(mText)){
//Do what you want(Edittext is NULL)
}else{
//Do what you want(Not NULL)
}
Try to get value from your edittext like below:
Globally declare variable : -
String editvalue;
In onCreate() :-
EditText youredittext = (EditText)findViewById(R.id.youredittextid);
editvalue = youredittext.getText.toString().trim();
Now in your condition check :
if(editvalue.isEmpty() || editvalue == null){
// Do what you want when editText's value is null or empty
}else{
}
You can also use
TextUtils.isEmpty(CharSequence str)
for empty and null string check.
Returns true if the string is null or 0-length

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
}
}

button is called twice with performClick()

I have a ImageButton plus. When click i need to do a inflate of a view.
My problem is that when i use performClick the Imagebutton is called twice, and execute two inflates simultaneously.
I don't why this happens.
Here is a little of my code:
private ImageButton addPhone;
addPhone = (ImageButton)view.findViewById(R.id.ac_ibAddClientPhone);
addPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inflationFields = new InflatationFields(getActivity());
inflationFields.inflateNewField("phone", containerPhone, view, adapterPhone);
}
});
and in another part of the code i call the button and try to click with perform click
try{
if(ccPhone.moveToFirst())
do{
if(flag_first==true){
phone = ccPhone.getString(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(ClientEditContact.class.getName(), "PHONE: " +phone);
type = ccPhone.getInt(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
etPhone = (EditText)viewPrincipal.findViewById(R.id.ac_etAddClientPhone);
etPhone.setText(phone + "" +etPhone.getTag().toString());
spPhone.setSelection(convertTypeToIdSpinner(type));
flag_first=false;
}
else if(flag_first == false){
addPhone.performClick();
phone = ccPhone.getString(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
type = ccPhone.getInt(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
etPhone = (EditText)viewContainerPhone.findViewWithTag("etTagPhone" + count);
etPhone.setText(phone + "" + etPhone.getTag().toString());
count = count + 1;
if(count==ccPhone.getCount()){
break;
}
}
}while(ccPhone.moveToNext());
Log.d(ClientEditContact.class.getName(), "LAST PHONE ---> " +phone);
}finally{
if(ccPhone != null && ! ccPhone.isClosed()){
ccPhone.close();
}
}
Anyone have any idea?
Double check the part of code from where you are calling addPhone.performClick();. May be that part is getting called twice.
Kind of late, but the system calls performClick() on its own when the button is clicked so you shouldnt use it in your code.

Login not working

I have written the simple code for Login authentication with hardcoded password.my problem is evenif I am entering the correct password my control is going in elese loop
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mynameeeeee",s1);
if(s1=="123")
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
Here's the problem :
You are storing a reference of the edit text content at creation time, when the edit text is empty.
You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :
Do the following :
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
btn.setOnClickListener ( new OnClickListener () {
#Override
public void onClick ( View v ) {
Log.d ( "mynameeeeee" , edt.getText().toString() );
if ( edt.getText().toString().equals ( "123" ) )
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
the string should be compared like:
if(s1.equals("123")) {}
Change your if statement like this
if(s1.equals("123"))
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
When comparing strings always use .equals() function
== Checks whether both the variable are referring to same object. In this case since they are referring to different object so the result of == is false.
use equals() method s1.equals("123") to check the content of the string object.

How to set my username and password in the code.?

Button loginbuttonbutton = (Button) findViewById(R.id.btnLogin);
loginbuttonbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(inputEmail.getText().toString() == "EdEffort#ncat.edu" &&
inputPassword.getText().toString() == "Steelers") {
Intent myIntent = new Intent(view.getContext(),
Host_Setting_PageActivity.class);
startActivityForResult(myIntent, 0);
} else {
System.out.println("Username or password is incorrect");
}
}
});
That is my code and the application actually start but whenever I hit the login button the application closes.
first use .equals() to compare strings.
== compares string refrences.Not value.
.equals() = compare strings character equality
if((inputEmail.getText().toString().equals("EdEffort#ncat.edu")&&inputPassword.getText().toString().equals("Steelers"))
And if force close than put logcat here..
use equals insead of == for String comparison
loginbuttonbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(inputEmail.getText().toString().equals("EdEffort#ncat.edu") && inputPassword.getText().toString().equals("Steelers") ){
Intent myIntent = new Intent(YOUR_CURRENT_ACTIVITY.this, Host_Setting_PageActivity.class);
startActivityForResult(myIntent, 0);
}
else{
System.out.println("Username or password is incorrect");
}
}
});
and make sure you are registering YOUR_CURRENT_ACTIVITY.this and Host_Setting_PageActivity.class both in manifest.xml
You should add
Host_Setting_PageActivity.class to your AndroidManifest
And also, you should compare strings always using .equals and not with "==" as "==" will really compare the instance of the string object and .equals will check the value of the string
dont use == method in if Condition but used .equals() method
like as
if(inputEmail.getText().toString().equals("abc") && inputPassword.getText().toString().equals("abc") ){
----------your code here-----------
}

Categories

Resources