Android: оператор If / else с string.equals, возвращающий визуальное подтверждение - PullRequest
0 голосов
/ 27 августа 2018

Я попытался написать пример приложения, которое проверяет пользовательский ввод (String 1) из EditText и сравнивает его со строкой (в данном случае translation 1).

После ответов и предложений я обновил свой Java-код и, насколько я могу судить, должен нормально работать, а я нет. (см. редактирование отладчика)

Заранее спасибо!

XML:

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.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">

<!-- Page Title -->
<TextView
    android:id="@+id/PageTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/test_title"
    android:textAlignment="center"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<!-- Input 1 -->
<EditText
    android:id="@+id/input1"
    android:layout_width="140dp"
    android:layout_height="40dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:inputType="text"
    android:text=""
    android:hint="@string/hint_input"
    app:layout_constraintEnd_toStartOf="@+id/translation1"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/PageTitle"
    android:imeOptions="actionNext"/>

<!-- Translation 1 -->
<TextView
    android:id="@+id/translation1"
    android:layout_width="140dp"
    android:layout_height="40dp"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="8dp"
    android:gravity="center"
    android:text="@string/test"
    android:textAlignment="center"
    android:textSize="18sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/input1"
    app:layout_constraintTop_toBottomOf="@+id/PageTitle"
    android:background="@drawable/translation_borders"/>

<!--Check button-->
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:onClick="Check"
    android:text="@string/check_btn"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="@+id/translation1"
    app:layout_constraintStart_toStartOf="@+id/input1"
    app:layout_constraintTop_toBottomOf="@+id/PageTitle" />

</android.support.constraint.ConstraintLayout>

РЕДАКТИРОВАТЬ: обновить код.

Java:

package com.bnf.Overhooring;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    String right = getString(R.string.right);
    String wrong = getString(R.string.wrong);

    EditText input1 = (EditText) findViewById(R.id.input1);
    String string1 = input1.getText().toString();
    String translation1 = "a";

    public void Check(View view) {
        if (string1.equals(translation1)) input1.setText(right);
        else input1.setText(wrong);
    }
}

РЕДАКТИРОВАТЬ: опубликованные результаты отладчика

Я запустил отладчик после обновления своего кода и обнаружил, что мое приложение закрывается при запуске. Ошибка в отладчике:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.bnf.overhooring, PID: 471
              java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.bnf.overhooring/com.bnf.overhooring.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                  at android.app.ActivityThread.-wrap14(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6776)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                  at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                  at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
                  at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
                  at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
                  at android.content.Context.getString(Context.java:476)
                  at com.bnf.overhooring.MainActivity.<init>(MainActivity.java:16)
                  at java.lang.Class.newInstance(Native Method)
                  at android.app.Instrumentation.newActivity(Instrumentation.java:1086)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
                  at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6776) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

Ответы [ 2 ]

0 голосов
/ 28 августа 2018

Несколько ошибок, на которые я хотел бы указать:

  • Не используйте отдельный блок { } для if-else
  • Не используйте System.out.println() для разработки Android, попробуйте Log.i() или любое другое Log утверждение.
  • Что касается визуального отображения, попробуйте использовать функцию EditText.setText() или TextView.setText(), чтобы показать визуальный вывод в вашем случае.
  • Чтобы следовать вышеприведенному пункту, вам сначала нужно инициализировать соответствующий View, например TextView или EditText на findViewById(), чтобы использовать setText() или getText().

Редактировать: Поскольку ваш код должен запускаться, когда активность раздувается из макета, поместите код после setContentView() в onCreate()

Я бы порекомендовал вам просмотреть официальное руководство разработчика для рефералов.

0 голосов
/ 28 августа 2018

Если вы хотите визуальное подтверждение на экране мобильного телефона, тогда вы можете показать его TextView или EditText. Вы можете установить текст на EditText input1, используя setText().

Например: input1.setText("Text");

TextView translation = (TextView) findViewById(R.id.translation1); 
translation.setText(input1.getText().toString());

Вы можете установить OnClickListener, используя:

Button btn = findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        //Your code goes here
   } 
});

Это берет значение из edittext, сравнивает и устанавливает текст, основанный на этом в текстовом представлении

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      EditText input1 = (EditText) findViewById(R.id.input1);

      String String1 = input1.getText().toString();

      String translation1 = "a";

      Button btn = findViewById(R.id.button);

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

          if(String1.equals(translation1)) {
              //System.out.print("This right!");
              translation.setText("This right!");
          } else {
              //System.out.print("This is wrong!");
              translation.setText("This wrong!"); 
          }
       } 
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...