Reputation: 67
Whenever I make a while loop in an app for android, it causes my screen to show only the basic background & action bar. It was very frustrating when I found this in my app, and I've spent the past couple hours attempting to find a workaround. I've made a very basic program trying to narrow down the cause and found it to be the while loop, which leaves me with a blank screen.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign Variables
EditText editText_HEX = (EditText)findViewById(R.id.EditText_HEX);
String stringHEX = editText_HEX.getText().toString();
Boolean isHex = stringHEX.matches("^#([A-Fa-f0-9]{6})$");
// I have (true) in right now, but if I change that to a more specific boolean I still
// can't see the page of my app.
while (true){
// Here I'm trying to get the loop to pause until the user enters 7 characters
// into the EditText box.
// I've tried while (editText_HEX.length() < 7) as well, but still get a blank page
while (stringHEX.length() < 7){
}
Toast.makeText(getApplicationContext(), "text reached 7 characters", Toast.LENGTH_SHORT).show();
break;
}
}
I'm not getting any error in the logcat- the app works fine, it just doesn't show any of my widgets. If I delete the while loop, it works.
What I'm ultimately trying to get: I'm trying to make an app that asks the user enter a hex value that will change the color of the background. In my previous question (which was answered), I figured out how to check for a valid hex. Now I want this loop running so that a person can enter a hex color into an EditText box, and the background color will instantly change; and if they re-enter a different hex into the textbox, the background will change once more. This while loop is just a simple program that I made to narrow down why my page was blank.
I've been working on different parts of an app in different projects. This is one- and then I'm planning on making the larger final app after I figure out the reasons for these errors and such. I'm new to programming for android, so if there is a simple fix to this I'd appreciate the help. Thanks!
Upvotes: 1
Views: 130
Reputation: 2295
By default the length of the text in the stringHEX is 0. And in onCreate itself even before the layout is shown, you have a while loop which is checking the length of stringHEX. Since it becomes an infinite while loop, you are not getting anything on the screen. Just to test, give a dummy text to your stringHEX in your xml and it should work fine.
Upvotes: 0
Reputation: 3283
Don't use a loop try this:
editText_HEX.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// check for valid hex here
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
Upvotes: 3