0

I have an app with a login page.

First, I have my MainActivity where everything starts:

public class MainActivity extends AppCompatActivity {

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

    // here i launch LoginActivity
    startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);

    emailText = findViewById(R.id.nav_text_email);
    usernameText = findViewById(R.id.nav_text_username);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == REQUEST_CODE){
        if(resultCode != Activity.RESULT_OK) {
            finish();
        }
        // if login succesful, i attach to variable instance of
        // logged user class.
        // that part works correct, in object vars exist
        loggedUser = loggedUser.getInstance();

        // i want to attach strings after succesful login
        emailText.setText(loggedUser.getEmail());
        usernameText.setText(loggedUser.getUsername());
    }
}

When run the app with the code above, after succesful LoginActivity app crashes with this exception:

2019-01-26 20:46:48.015 13071-13071/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 13071
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6523)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:89)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
    at android.app.Activity.performResume(Activity.java:7022)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2876) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:156) 
    at android.app.ActivityThread.main(ActivityThread.java:6523) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 

When I deleted the setText() methods from `onActivityResult(), I don't get that exception. The error appears when I click the Login button and the app crashes.

While debugging, compiler not even go in lines with setText()

My question is, how to set texts in textviews in the scenario that I coded above?

UPDATE

Even if i popualte strings in loggedUser in constructor as empty, move loggedUser = loggedUser.getInstance() and move setText() to onCreat, i still get that NPE.

EDIT:

I added onResume method:

@Override
protected void onResume()
{
    if(isLogged) {
        emailText.setText(loggedUser.getEmail());
        usernameText.setText(loggedUser.getUsername());
    }
    super.onResume();
}

And edited onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == REQUEST_CODE){
        if(resultCode != Activity.RESULT_OK) {
            finish();
        }
        isLogged = true; //var for if statement in onResume()
        loggedUser = loggedUser.getInstance();
    }
}

And i still get the same error on onResume() method when i setting up TextViews.

2019-01-26 21:21:57.752 18262-18262/com.example.admin.keystroke_dynamics E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.keystroke_dynamics, PID: 18262
java.lang.RuntimeException: Unable to resume activity {com.example.admin.keystroke_dynamics/com.example.admin.keystroke_dynamics.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3586)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6523)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.example.admin.keystroke_dynamics.Activities.MainActivity.onResume(MainActivity.java:90)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1279)
    at android.app.Activity.performResume(Activity.java:7022)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3561)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3626) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1618) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:156) 
    at android.app.ActivityThread.main(ActivityThread.java:6523)
michasaucer
  • 4,562
  • 9
  • 40
  • 91

3 Answers3

1

A null view is usually a result of your layout not containing a view with the id you specified in findViewById(). Therefore findViewById() returns null and the variables are remaining null when onResume() is called. Double check your view ids in main_activity.xml.

It's also possible that the full content view is not available in onCreate() if you are using a more complicated layout. If you find that your views are null in onCreate(), try moving findViewById() to a later point in the lifecycle.

Greg Moens
  • 1,705
  • 8
  • 15
  • Maybe i should mentioned that, but the `textviews` are in diffrent layout files than `main_activity.xml` (the `MainActivity.java` content vire). I have `main_activity` where is `NavigationView` with my sidebar where i store that textviews (textviews are in diffrent file than `main_activity` – michasaucer Jan 26 '19 at 20:54
  • They should be found, unless the other layout is not inflated in time for them to exist in onCreate(). Just for fun, did you try moving the findViewById() lines into onResume()? – Greg Moens Jan 26 '19 at 21:15
  • I tried it before you mentioned about `onResume()`. same history – michasaucer Jan 26 '19 at 21:16
  • Nah, now it works, i moved `findbyid` to `onResume()` and it works! Could you tell me, what happend there? Why textviews was null in onCreate? – michasaucer Jan 26 '19 at 21:19
  • Answer updated. I'd have to debug NavigationView to figure out what's going on, but it would seem that there is some delayed layout inflating going on. – Greg Moens Jan 26 '19 at 21:45
  • That bug is SO weird. On emulator on my PC all works fine, but on my android device (Huawei P9, API 24) it started to crashes. Yesterday all works fine. Just saying, i think i will do another SO topic for that bug – michasaucer Jan 27 '19 at 09:23
  • definitely don't want to sleep in a lifecycle method, you'll cause an Android Not Responding error! – Greg Moens Jan 27 '19 at 20:53
0

Try reordering the code like this

emailText = findViewById(R.id.nav_text_email);
usernameText = findViewById(R.id.nav_text_username);
startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);
Charan M
  • 489
  • 3
  • 7
0

Try initializing the variables before accessing them.

public class MainActivity extends AppCompatActivity {
TextView emailText;
TextView usernameText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // here i launch LoginActivity
    startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE);

    emailText = findViewById(R.id.nav_text_email);
    usernameText = findViewById(R.id.nav_text_username);
}

Could fit in a comment

You need to access the NavigationView from the activity

Update

NavigationView navigationView = findViewById(R.id.nav_id)
View header = navigationView.getHeaderView(0)
TextView usernameText = header.findViewById(R.id.username_text_view_id);
christoandrew
  • 437
  • 4
  • 17