如何解决我的Android中的NullPointerException问题

时间:2018-08-06 19:35:00

标签: android android-layout android-studio dialog

我已经使用WebView创建了android应用

功能正常,但是当我添加私有void createDialog()来显示alertdialog时,则会出现此错误:

  

NullPointerException:尝试调用虚拟方法'void   android.app.Dialog.show()'

关于Logcat中的空对象引用

这是我的片段代码:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public Dialog mDialog;
    public Button mDialogyes, mDialogno;

    ProgressBar progressBar;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        webView=(WebView) findViewById(R.id.webView);

        webView.setVisibility(View.INVISIBLE);
        webView.loadUrl("http://m.jazz.com.pk/smart/wifi_3g.html");
        WebSettings webSettings=webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                setProgressBarVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                setProgressBarVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                setProgressBarVisibility(View.GONE);
            }
        });
        webView.loadUrl("http://m.jazz.com.pk/smart/wifi_3g.html");


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


            }
        });

        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.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(this);

        ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activenetnetwork = cm.getActiveNetworkInfo();
        if(activenetnetwork != null)
        {
            if(activenetnetwork.getType() == ConnectivityManager.TYPE_WIFI)
            {
                //Toast.makeText(getApplicationContext(),activenetnetwork.getTypeName(),Toast.LENGTH_LONG).show();
            }else if(activenetnetwork.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                //Toast.makeText(getApplicationContext(),activenetnetwork.getTypeName(),Toast.LENGTH_LONG).show();
            }
        }else {

            ActionBar actionBar =  getSupportActionBar();
            actionBar.setTitle("Web page not available");
            Toast.makeText(getApplicationContext(),"Please Check your Internet ",Toast.LENGTH_LONG).show();
        }


    }

    private void setProgressBarVisibility(int visibility) {
        // If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
        if (progressBar != null) {
            progressBar.setVisibility(visibility);
        }
    }

    private void createDialog() {
        mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setContentView(R.layout.dialog_exit);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);
        mDialogyes = (Button) mDialog.findViewById(R.id.yes);
        mDialogno = (Button) mDialog.findViewById(R.id.no);



        mDialogyes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
                finish();
                System.exit(0);


            }

        });

        mDialogno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });


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

    }

    @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.home) {


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

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

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

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

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

        }

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

2 个答案:

答案 0 :(得分:2)

看代码,永远不会调用方法createDialog(),因此mDialog的值始终为空。您需要先初始化对话框(即通过调用createDialog()),然后才能在mDialog.show();覆盖中调用onBackPressed()

答案 1 :(得分:0)

在调用show方法之前需要对空指针进行检查。示例:

if (mDialog != null) {
    mDialog.show(); 
}

如上所述,您的mDialog为null,因为您需要先调用createDialog方法。无论您从另一个应用程序复制的任何代码都遗漏了某些东西。