Runtime Crash Upon Activity Selection

喜夏-厌秋 提交于 2019-12-02 13:02:23

First, when there is a crash, there is an exception stacktrace in logcat and it is very helpful in debugging problems. You should learn to use it. See: Unfortunately MyApp has stopped. How can I solve this?

Second, your activity is not yet doing really anything. One crash reason is that you're calling findViewById() too early in the activity lifecycle, before the activity has a window and before you've set a layout with the views to be found. Move the findViewById() calls to onCreate() after setContentView().

First of all, make sure your always add your crash details printed in logcat, which is found in lower part of your screen, as you see in the image below > 6:LOGCAT

Second, when you want to assign a view to variable, you should make sure the view hierarchy is built. the assignment findViewById(R.id.someID) looks for a view, but when you call it before the parent view is built you will get a null pointer exeption. make sure you call this method always after setContentView(R.layout.activity_customize) of onCreate() method.

3rd point that comes to my mind is that try to name your variable meaningful. a, b and c are NOT going to remind you what are they doing in ten days or so. Name your variables descriptive. Ask yourself what they do and why do you need them, your answer to those question will help you find a right name for them. I chose some example for just not being a, b, c! So, make your code as below;

in the class, and before onCreate() :

EditText exerciseHoursEditText;
EditText sleepHoursEditText;
EditText mmHoursEditText;
EditText oaHoursEditText;
TextView healthTotalTextView;

and in onCreate() :

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customize);
exerciseHoursEditText = (EditText) findViewById(R.id.exerciseHours);
sleepHoursEditText = (EditText) findViewById(R.id.sleepHours);
mmHoursEditText = (EditText) findViewById(R.id.mmHours);
oaHoursEditText = (EditText) findViewById(R.id.oaHours);
healthTotalTextView = (TextView) findViewById(R.id.healthTotal);

Android works in this way, perhaps you should read a little about android activity life cycle. it's pretty simple. check this link

4th point that is worth mentioning, is that you must be cautious when using methods which might result in NULL. What you are doing in a.getText().toString() might cause in NPE, so always check as below:

   if(a.getText() != null) {
        a.getText().toString() .... 
    }

I hope you enjoy what you are doing ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!