Home > Net >  Android Studio: Taking a Character from a String
Android Studio: Taking a Character from a String

Time:09-23

Can someone help? every time when I click the button, it crashes, I just want to get a character from a string, but can't cuz it will crash...

package com.example.shuffleword;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText word;
    Button start;
    TextView wordprev;


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

        word = (EditText)findViewById(R.id.word);
        start = (Button)findViewById(R.id.start);
        wordprev = (TextView)findViewById(R.id.wordprev);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = word.getText().toString();
                char first = name.charAt(0);
                wordprev.setText(first);
            }
        });
    }
}

CodePudding user response:

start.setOnClickListener(a -> {
     String name = word.getText().toString();
   
     wordprev.setText(name.trim().isEmpty() ? "Name is Empty or Null" : String.valueOf(name.trim().charAt(0)));
});

This will just check if the string name is empty then the TextView will display "Name is Empty or Null" and if the name is not empty then it will display the first char or fire letter from the string name.

  • Related