Issue
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);
}
});
}
}
Solution
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.
Answered By - Viknesh TPK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.