mercredi 27 novembre 2019

If ... Else statement seems to be returning the wrong output

I am just exploring different methods to test out Log class in java, where I use Log.d() if a certain text view is shown and Log.e() to log an exception error if otherwise.

However, the logcat seems to be showing the opposite output instead. Why is that so?

My main activity code:

package com.example.dummy_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (findViewById(R.id.editText).toString().equals("Happy Birthday!")) {
            Log.d("logMessage", "correct message shown");
        } else {
            Log.e("logMessage", "exception error");
        }
    }
}

XML --

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Happy Birthday!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The logcat is showing "exception error" instead of "correct message shown". I have also tried removing the toString() but it still shows the same result. Can anyone explain why? enter image description here

Aucun commentaire:

Enregistrer un commentaire