Android Drawer项目不起作用

时间:2016-03-24 16:49:10

标签: java android

我在android studio中创建了一个抽屉菜单并更改了抽屉的项目。我想在项目点击时启动另一个活动或查看另一个布局。但我得到以下错误,应用程序停止。

03-24 21:38:28.202 2227-10289/? D/GassUtils: Found app info for package    com.example.imran.myapp:1. Hash: 6b9333e031907d7a6a6c12cd9fdfa0d23bd13ee0f40c9617ddd005dc358321b0
03-24 21:38:28.202 2227-10289/? D/k: Found info for package com.example.imran.myapp in db.
03-24 21:38:38.722 1035-1167/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:38.782 9789-9789/? I/Timeline: Timeline: Activity_launch_request id:com.example.imran.myapp time:121627337
03-24 21:38:38.802 1035-1853/? W/ActivityManager: NORMAL SET : srcAppInfo.processName = com.example.imran.myapp, destAppInfo.processName = com.example.imran.myapp
03-24 21:38:38.802 1035-1853/? W/ActivityManager: startActivity called from finishing ActivityRecord{28b176ac u0 com.example.imran.myapp/.MainActivity t2394 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.example.imran.myapp/.Home (has extras) }
03-24 21:38:38.802 1035-1853/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:39.402 1035-1532/? I/WindowManager: Switching to real app window: Window{11c67d3b u0 com.example.imran.myapp/com.example.imran.myapp.Home}
03-24 21:38:39.622 1035-1069/? I/Timeline: Timeline: Activity_windows_visible id: ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396} time:121628177
03-24 21:38:58.462 9789-9789/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.example.imran.myapp, PID: 9789
                                             java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
                                                 at com.example.imran.myapp.Home.onNavigationItemSelected(Home.java:120)
                                                 at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:146)
                                                 at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                 at android.support.v7.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:84)
                                                 at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
                                                 at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                 at android.support.design.internal.NavigationMenuPresenter.onItemClick(NavigationMenuPresenter.java:196)
                                                 at android.widget.AdapterView.performItemClick(AdapterView.java:334)
                                                 at android.widget.AbsListView.performItemClick(AbsListView.java:1536)
                                                 at android.widget.AbsListView$PerformClick.run(AbsListView.java:3683)
                                                 at android.widget.AbsListView$3.run(AbsListView.java:5604)
                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:145)
                                                 at android.app.ActivityThread.main(ActivityThread.java:6145)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.462 1035-1514/? W/ActivityManager:   Force finishing activity com.example.imran.myapp/.Home
03-24 21:38:58.462 1035-1514/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: processName: com.example.imran.myapp
03-24 21:38:58.542 1035-1035/? D/CrashAnrDetector: broadcastEvent : com.example.imran.myapp data_app_crash
03-24 21:38:58.992 1035-1062/? W/ActivityManager: Activity pause timeout for ActivityRecord{dca1b0 u0 com.example.imran.myapp/.Home t2396 f}

Java文件: Home.java

package com.example.imran.myapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
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;
import android.widget.Button;
import android.widget.TextView;

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    Button logout = (Button) findViewById(R.id.logout_button);
    TextView text1 = (TextView) findViewById(R.id.result_sms);
    final UserLocalStore loginuser = new UserLocalStore(getApplicationContext());
    SharedPreferences mPrefs = getSharedPreferences("userDetails",0);
    String str1=(mPrefs.getString("fullname","Default_Value"));
    String email = loginuser.getLoggedInUser().email;
    text1.setText("Welcome "+str1+"- Your email: "+email);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loginuser.clearUserData();
            //startActivity(new Intent(getApplicationContext(), MainActivity.class));

            finish();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            //setContentView(R.layout.activity_main);
        }
    });





    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 = (NavigationView) findViewById(R.id.nav_view);
    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.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.
    int id = item.getItemId();

    if (id == R.id.nav_photos) {
        // Handle the camera action
        //setContentView(R.layout.myaccount);
    } else if (id == R.id.nav_myaccount) {
        setContentView(R.layout.activity_myaccount2);
      //
    } else if (id == R.id.nav_logout) {
        UserLocalStore loginuser = new UserLocalStore(this);
        loginuser.clearUserData();

        finish();
        startActivity(new Intent(getApplicationContext(), MainActivity.class));
    }

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

在home.java的最后一部分,当我添加setContentView(R.layout.activity_myaccount2); 时,应用程序崩溃了。

1 个答案:

答案 0 :(得分:1)

这里的问题是在调用drawer.closeDrawer();时出现空指针异常,正如您所说,在setContentView(R.layout.activity_myaccount2);被调用后会发生这种情况。

通过使用setContentView,您将整个布局替换为另一个布局,在这种情况下,您似乎将包含R.id.drawer_layout的布局替换为另一个不包含它的布局。当您尝试使用findViewById和closeDrawer时,当包含抽屉的布局不再存在时,会发生空指针异常,使用setContentView将其替换为另一个。

要解决此问题,您可能需要重新考虑如何构建应用并显示不同的内容。作为一个起点,我建议使用包含您的抽屉和片段的活动来查找示例,以显示不同的内容。活动和抽屉始终存在,只有片段发生变化,如this tutorial