NAVIGATION DRAWER :- NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()

Vitesh

DRAWER IMAGEHello friends i'm using Navigation drawer in my project but facing with the above error while trying to open an activity onclick of listview-listitem (2nd time) the app run perfectly at very first time when we click on the list item but if we go back and click any item of drawer menu and after that if we try to click on listitem the error occurs LIST VIEW

FRAGMENT.java


package com.forever.technology.bscit;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.forever.technology.bscit.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class Sem1Fragment_list extends ListFragment {




    public Sem1Fragment_list() {
        // Required empty public constructor
    }
    ListView lv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sem1_list, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.sem1, android.R.layout.simple_list_item_1);
        setListAdapter(adapter);

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        switch (position)
        {
            case 0:
                Intent intent = new Intent(getContext(),Subject1Activity.class);
                startActivity(intent);
        }

    }
}

MAIN ACTIVITY

package com.forever.technology.bscit;

import android.content.ComponentName;
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.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;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;

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

        //Set the fragment initially
        HomeFragment fragment = new HomeFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.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);

        //How to change elements in the header programatically

      /*  View headerView = navigationView.getHeaderView(0);
        TextView emailText = (TextView) headerView.findViewById(R.id.email);
        emailText.setText("[email protected]"); */

        navigationView.setNavigationItemSelectedListener(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.main, 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.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            //Set the fragment initially
            HomeFragment fragment = new HomeFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
            // Handle the camera action
        } else if (id == R.id.nav_sem1) {
            //Set the fragment initially
            Sem1Fragment fragment = new Sem1Fragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
            // Handle the camera action
        } else if (id == R.id.nav_sem2) {
            //Set the fragment initially
            Sem2Fragment fragment = new Sem2Fragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_sem3) {

        } else if (id == R.id.nav_sem4) {

        } else if (id == R.id.nav_sem5) {

        } else if (id == R.id.nav_sem6) {

        }
        else if (id == R.id.nav_blogs) {

        }
        else if (id == R.id.nav_site) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Subject1.activity

package com.forever.technology.bscit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Subject1Activity extends AppCompatActivity {

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

LOGCAT

03-23 01:06:33.111 11547-11547/com.compscitutorials.basigarcia.navigationdrawervideotutorial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.compscitutorials.basigarcia.navigationdrawervideotutorial, PID: 11547
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
   at android.content.ComponentName.<init>(ComponentName.java:128)
   at android.content.Intent.<init>(Intent.java:4449)
   at com.forever.technology.bscit.Sem1Fragment_list.onListItemClick(Sem1Fragment_list.java:50)
   at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
   at android.widget.AdapterView.performItemClick(AdapterView.java:310)
   at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
   at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
   at android.widget.AbsListView$3.run(AbsListView.java:3903)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Prudhvi

If my understanding is correct, you're starting a different Fragment Sem1Fragment from the MainActivity. So the actual Fragment which has the list i.e Sem1Fragment_list is not having the context needed to launch Subject1Activity. So just replace the Sem1Fragment with Sem1Fragment_list in your Navigation Drawer code as shown below.

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;

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

        //Set the fragment initially
        HomeFragment fragment = new HomeFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.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);

        //How to change elements in the header programatically

      /*  View headerView = navigationView.getHeaderView(0);
        TextView emailText = (TextView) headerView.findViewById(R.id.email);
        emailText.setText("[email protected]"); */

        navigationView.setNavigationItemSelectedListener(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.main, 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_about) {
            return true;
        }
        if (id == R.id.action_exit) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(false);
            builder.setMessage("Do you want to Exit?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //if user pressed "yes", then he is allowed to exit from application
                    finish();
                }
            });
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //if user select "No", just cancel this dialog and continue with app
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        if (id == R.id.nav_home) {
            //Set the fragment initially
            HomeFragment fragment = new HomeFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
            // Handle the camera action
        } else if (id == R.id.nav_sem1) {
            //Set the fragment initially
            Sem1Fragment_list fragment = new Sem1Fragment_list();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.addToBackStack(null); //add this to restore the fragment when back button is pressed
            fragmentTransaction.commit();
            // Handle the camera action
        } else if (id == R.id.nav_sem2) {
            //Set the fragment initially
            Sem2Fragment fragment = new Sem2Fragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

        } else if (id == R.id.nav_sem3) {

        } else if (id == R.id.nav_sem4) {

        } else if (id == R.id.nav_sem5) {

        } else if (id == R.id.nav_sem6) {

        }
        else if (id == R.id.nav_blogs) {

            try {
                //If App installed
                Intent intent;
                intent = getPackageManager().getLaunchIntentForPackage("com.forevertech.app");
                startActivity(intent);
            } catch (Exception e) { //google play app is not installed
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.forevertech.app"));
                startActivity(intent);
            }
        }
        else if (id == R.id.nav_site) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("http://www.abaagekya.com/"));
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager

From Java

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

From Java

Can't retrieve data from firebase (java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String)

From Dev

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method android

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()'

From Dev

How to resolve Java.lang.NullPointerException: Attempt to invoke virtual method?

From Dev

NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

From Dev

error:Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

From Dev

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

From Dev

Android: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

From Dev

NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

From Dev

com.android.volley.VolleyError:java.lang.NullPointerException:Attempt to invoke virtual method 'in java.lang.String.length()' on object reference

From Dev

Android. Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Editor$SelectionModifierCursorController.show()'

From Dev

NullPointerException: Attempt to invoke virtual method 'java.lang.String com.zopim.android.sdk.model.VisitorInfo.getEmail()' app is forced close

From Dev

Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)

From Dev

How to resolve Java.lang.NullPointerException: Attempt to invoke virtual method?

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener

From Dev

Android. Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

From Dev

com.android.volley.VolleyError:java.lang.NullPointerException:Attempt to invoke virtual method 'in java.lang.String.length()' on object reference

From Dev

Android Studio - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference

From Dev

Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object

From Dev

Android exception Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)

From Dev

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()

From Dev

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName() on getActivity()

From Dev

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser

Related Related

  1. 1

    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager

  2. 2

    java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

  3. 3

    Can't retrieve data from firebase (java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String)

  4. 4

    NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

  5. 5

    java.lang.NullPointerException: Attempt to invoke virtual method android

  6. 6

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()'

  7. 7

    How to resolve Java.lang.NullPointerException: Attempt to invoke virtual method?

  8. 8

    NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

  9. 9

    error:Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

  10. 10

    Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

  11. 11

    Android: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

  12. 12

    NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

  13. 13

    com.android.volley.VolleyError:java.lang.NullPointerException:Attempt to invoke virtual method 'in java.lang.String.length()' on object reference

  14. 14

    Android. Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

  15. 15

    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Editor$SelectionModifierCursorController.show()'

  16. 16

    NullPointerException: Attempt to invoke virtual method 'java.lang.String com.zopim.android.sdk.model.VisitorInfo.getEmail()' app is forced close

  17. 17

    Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)

  18. 18

    How to resolve Java.lang.NullPointerException: Attempt to invoke virtual method?

  19. 19

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

  20. 20

    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener

  21. 21

    Android. Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

  22. 22

    com.android.volley.VolleyError:java.lang.NullPointerException:Attempt to invoke virtual method 'in java.lang.String.length()' on object reference

  23. 23

    Android Studio - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener

  24. 24

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference

  25. 25

    Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object

  26. 26

    Android exception Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)

  27. 27

    Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()

  28. 28

    Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName() on getActivity()

  29. 29

    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser

HotTag

Archive