简体   繁体   中英

Android error in Navigation activity

I am having a Navigation activity in my Android Application.I used the default template from Android studio for creating the navigation drawer. Following is the code in Nav_headder_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
    android:gravity="bottom">

    <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:id="@+id/Name"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        />

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:id="@+id/mailId" />

</LinearLayout>

I am trying to set the value of the TextView from the Java file dynamically. Below is the java code:

package example.android.webdroid.loginapplication;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import example.android.webdroid.loginapplication.Util.User;
import example.android.webdroid.loginapplication.Util.UserDataStore;
import example.android.webdroid.loginapplication.fragments.UpdateProfile;

public class Home extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

TextView tvUserName,tvMailId;
UserDataStore userData;
String auth="no";
Toolbar toolbar;
NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
   // Intent i=getIntent();
    /*if(i!=null) {
        auth = i.getExtras().getString("auth");
    }*/
    //To set up MainFragment - Uncomment this
    /*MainFragment fragment =new MainFragment();
    FragmentTransaction fragTran=getSupportFragmentManager().beginTransaction();
    fragTran.replace(R.id.displayPage,fragment);
    fragTran.commit();*/
     toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    tvUserName=(TextView)navigationView.findViewById(R.id.Name);
    tvMailId=(TextView)navigationView.findViewById(R.id.mailId);
    userData=new UserDataStore(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    switch (item.getItemId()){
    case R.id.nav_contact:
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:000000"));
        startActivity(intent);
        break;
    case R.id.nav_updateProfile:
        UpdateProfile fragment =new UpdateProfile();
        FragmentTransaction fragTran=getSupportFragmentManager().beginTransaction();
        fragTran.replace(R.id.displayPage, fragment);
        fragTran.commit();
        break;
     case R.id.nav_logout:
         userData.ClearUserData();
         userData.setUserLoggedIn(false);
         startActivity(new Intent(this,Login.class));
         break;
      default:
            break;
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
@Override
protected void onStart() {
    super.onStart();
   if(authentiateUser()){
        displayUserDetails();
    }
    else {
        startActivity(new Intent(this, Login.class));
    }

}
public void displayUserDetails(){
    User user=userData.getLoggedInUserData();
    if(user==null){
        System.out.println("LoginAppln_Nag User null=========");
    }
    else {
        System.out.println("LoginAppln_Nag User not null=========" + user.mailId + user.customerId);
       tvUserName.setText("Welcome " + user.mailId);
        tvMailId.setText(user.name);
    }
}

public boolean authentiateUser(){
    return userData.getUserLoggedIn();
}

}

Following is the code for activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:fitsSystemWindows="true" tools:openDrawer="start">

    <include layout="@layout/app_bar_home" android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView android:id="@+id/nav_view"
        android:layout_width="wrap_content" android:layout_height="match_parent"
        android:layout_gravity="start" android:fitsSystemWindows="false"
        app:headerLayout="@layout/nav_header_home" app:menu="@menu/activity_home_drawer" />

</android.support.v4.widget.DrawerLayout>

I get the NullPointerException while setting value for the TextView field.

 java.lang.RuntimeException: Unable to start activity ComponentInfo{example.android.webdroid.loginapplication/example.android.webdroid.loginapplication.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
12-29 21:25:48.640 24076-24076/example.android.webdroid.loginapplication E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2390

)

I am trying to set the Name in the Headder part of the navigation drawer. The text view in the Navigation drawer will be visible only when it is pulled out. I am new to Android programming and I am not sure,is there any different way to set the Text view in the Navigation drawer

If your views are in Navigation view .Try finding the view from navigation view

tvUserName=(TextView) navigationView.findViewById(R.id.Name);
tvMailId=(TextView) navigationView.findViewById(R.id.mailId);

You're inflating activity_home.xml as your Activity main layout :

setContentView(R.layout.activity_home);

And you assign the TextViews like this :

tvUserName=(TextView)findViewById(R.id.Name);
tvMailId=(TextView)findViewById(R.id.mailId);

but those TextView are included in a layout called Nav_headder_main.xml , and you're looking for them in the layout ( activity_home.xml )

You need to look for those TextView in the correct layout, or they will come out as null , try this :

tvUserName=(TextView) navigationView.findViewById(R.id.Name);
tvMailId=(TextView) navigationView.findViewById(R.id.mailId);

EDIT : the above assumes you at least inflated Nav_header_main.xml somewhere in your Activity main layout, for example with include :

<include 
    id="@+id/nav_view"
    layout="@layout/Nav_header_main"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM