i am getting this NullPointerException Error in Java trying to run my app in android Studio. Below is my JavaFile
package com.example.app;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.app.AboutusFragment;
import com.example.app.AddProductFragment;
import com.example.app.AllProductsFragment;
import com.example.app.CartFragment;
import com.example.app.CategoryFragment;
import com.example.app.CatlistFragment;
import com.example.app.ChangePwdFragment;
import com.example.app.ContactusFragment;
import com.example.app.HomeFragment;
import com.example.app.LoginFragment;
import com.example.app.MediMartDbHelper;
import com.example.app.MediMartUtils;
import com.example.app.OrderHistoryFragment;
import com.example.app.OrdersFragment;
import com.example.app.R;
import com.example.app.RegisterFragment;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout dlayout;
private NavigationView nav;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
private SharedPreferences sp;
private MediMartDbHelper db;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
init();
drawerToggle=new ActionBarDrawerToggle(this.getParent(),dlayout,toolbar,R.string.on,R.string.Off);
dlayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
nav.setNavigationItemSelectedListener(this);
permissions();
MediMartUtils.loadFragment(this,new CategoryFragment());
loadmenu();
}
public void init(){
dlayout=findViewById(R.id.dlayout);
nav= findViewById(R.id.nav_view);
toolbar= findViewById(R.id.toolbar);
tv= nav.getHeaderView(0).findViewById(R.id.tvusername);
sp=getSharedPreferences("users",MODE_PRIVATE);
db=new MediMartDbHelper(this);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("My Shop");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId()==R.id.mcart){
String user=sp.getString("userid","guest");
if(user.equals("guest")) {
MediMartUtils.loadFragment(this, new LoginFragment());
Snackbar.make(getCurrentFocus(),"Please Login First",BaseTransientBottomBar.LENGTH_LONG).show();
}else{
MediMartUtils.loadFragment(this, new CartFragment());
}
}
return super.onOptionsItemSelected(item);
}
public void loadmenu(){
String user=sp.getString("userid","guest");
Menu menu=nav.getMenu();
switch(user) {
case "guest":
Log.d("Nauman", " i am in loadmenu: " + user);
menu.setGroupVisible(R.id.gadmin, false);
menu.setGroupVisible(R.id.guser, false);
menu.setGroupVisible(R.id.gcustomer, false);
tv.setText("Welcome Guest");
break;
case "admin":
Log.d("Nauman", " i am in loadmenu: " + user);
menu.setGroupVisible(R.id.gadmin, true);
menu.setGroupVisible(R.id.guser, true);
menu.setGroupVisible(R.id.gcustomer, false);
tv.setText("Welcome Administrator");
break;
default:
Log.d("Nauman", " i am in loadmenu: " + user);
menu.setGroupVisible(R.id.guser, true);
menu.setGroupVisible(R.id.gcustomer, true);
menu.setGroupVisible(R.id.gadmin, false);
Cursor c=db.findcustomer(user);
c.moveToNext();
tv.setText("Welcome "+c.getString(1));
break;
}
}
private void permissions(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.CALL_PHONE},100);
}
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},200);
}
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment f=null;
switch (item.getItemId()){
case R.id.mhome:
f=new HomeFragment();
break;
case R.id.mcat:
f=new CatlistFragment();
break;
case R.id.mnoti:
f=new OrderHistoryFragment();
break;
case R.id.mproducts:
f=new CategoryFragment();
break;
case R.id.morders:
f=new OrdersFragment();
break;
case R.id.mchangepwd:
f=new ChangePwdFragment();
break;
case R.id.maddpro:
f=new AddProductFragment();
break;
case R.id.mshowall:
f=new AllProductsFragment();
break;
case R.id.mlogout:
SharedPreferences.Editor edit=sp.edit();
edit.remove("userid");
edit.remove("role");
edit.commit();
f=new CategoryFragment();
Toast.makeText(this, "Sign out successfully..", Toast.LENGTH_SHORT).show();
dlayout.closeDrawer(GravityCompat.START);
return MediMartUtils.loadwithoutHistoryFragment(this,f);
case R.id.mcart:
f=new CartFragment();
break;
}
dlayout.closeDrawer(GravityCompat.START);
return MediMartUtils.loadFragment(this,f);
}
@Override
public void onBackPressed() {
if(dlayout.isDrawerOpen(GravityCompat.START)){
dlayout.closeDrawer(GravityCompat.START);
}
if(getSupportFragmentManager().getBackStackEntryCount()==0) {
super.onBackPressed();
}else{
getSupportFragmentManager().popBackStack();
}
}
public void login(View view) {
MediMartUtils.loadFragment(this,new LoginFragment());
}
public void register(View view) {
MediMartUtils.loadFragment(this,new RegisterFragment());
}
public void contactus(View view) {
MediMartUtils.loadFragment(this,new ContactusFragment());
}
public void aboutus(View view) {
MediMartUtils.loadFragment(this,new AboutusFragment());
}
}
Here is my activity home layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.come/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
tools:context=".MainActivity"
android:id="@+id/dlayout">
<include
layout="@layout/main_content"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer_menu"
/>
</androidx.drawerlayout.widget.DrawerLayout>
And here, where the id tvusername is assigned
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="220dp"
android:background="#ffffff"
android:layout_gravity="top"
android:orientation="vertical"
android:padding="10dp">
<ImageView
android:layout_width="150dp"
android:layout_height="100dp"
android:id="@+id/imageView14"
app:srcCompat="@drawable/grocerrylogo"/>
<TextView
android:id="@+id/textView28"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="Shopify Cart"
android:textColor="#8F10a5"
android:textSize="25dp"/>
<TextView
android:id="@+id/tvusername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Welcome Guest"
android:textColor="#640873"
android:textSize="18dp"
android:textStyle="bold"/>
</LinearLayout>
I have seen plenty of similiar post but and i tried to learn from them but it doesnt resonate within me. I truly do not understand why this error is thrown in line 75 which is this one:
tv= nav.getHeaderView(0).findViewById(R.id.tvusername);
And Line 61 which is this one: (probably because the error first comes from within the method)
init();
I can imagine that the error is pretty obvious and im just unable to see it:D Thanks alot!
If i have to provide any more information please let me know, this is my first posts on here.
I am trying to assign a ressource id to TextView tv; And i am getting the error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.app.HomeActivity.init(HomeActivity.java:75)
at com.example.app.HomeActivity.onCreate(HomeActivity.java:61)
I am not sure why its not working and where the error seems to be
change your code like as follow
tv = nav.findViewById(R.id.tvusername);
Please accept this answer if it solved your problem or was the most helpful in finding your solution
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.