Android的NullPointerException异常处理

Android的NullPointerException异常处理

本文介绍了Android的NullPointerException异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Andr​​oid应用程序总是崩溃当我点击鱼选项,并没有什么插入设置活动这是一个空指针异常,我试图处理它,但没有结果,所以这里是我的codeSelectPetsScreen Acivity

 包com.set.petshome;
公共类SelectPetsScreen延伸活动{
    鱼缸II =新鱼缸();
    的ImageButton fButton,sButton,TButton的;
    按钮chButton,setsButton;
      私人的MediaPlayer MP0,MP1;
      公共字符串值;
      最终的上下文语境=这一点;
      字符串numvalue;
    FirstSSettings testObj =新FirstSSettings();
        //公共字符串chnumber; //收件人的手机号码
        公共字符串NUM;

    @覆盖
    公共无效的onCreate(包savedInstanceState){

        super.onCreate(savedInstanceState);
        的setContentView(R.layout.selectscreen);
                    //菜单启动声音code
      MP0 = MediaPlayer.create(这一点,R.raw.menu);
        mp0.start();

        //结束菜单声音code

        //设置按钮启动
        setsButton =(按钮)findViewById(R.id.settingsb);
        setsButton.setOnClickListener(新OnClickListener(){
             公共无效的onClick(查看为arg0){
                    //语音
                    MP1 = MediaPlayer.create(getBaseContext(),R.raw.menu);
                    mp1.start();
                    //结束语音
                    //开始一个新的意图

                    意图nextScreen =新的意图(getApplicationContext(),FirstSSettings.class);
                    startActivity(nextScreen);

                }
            });

        //设置按钮结束


        //第二章No.Button开始
            chButton =(按钮)findViewById(R.id.changebutton);
            //添加按钮监听器
                    chButton.setOnClickListener(新OnClickListener(){


                        @覆盖
                        公共无效的onClick(查看为arg0){

                            //自定义对话框
                            最后一个对话框对话框=新的对话框(背景);
                            dialog.setContentView(R.layout.mycustom);
                            dialog.setTitle(更改号码);

                            //设置自定义对话框组件 - 文字,图片和按钮
                            TextView的电流=(TextView中)dialog.findViewById(R.id.cn);
                            current.setText(当前数量:);
                        //current.setText("Current号:);
                        TextView的ET11 =(TextView中)dialog.findViewById(R.id.et1);
                        //et1​​1.setKeyListener(null);

                        et11.setText(FirstSSettings.getUserNumber());

                        TextView的newnum =(TextView中)dialog.findViewById(R.id.nn);
                        newnum.setText(新号码);
                        TextView的et22 =(TextView中)dialog.findViewById(R.id.et2);
                        et22.setText();






                        // ImageView的形象=(ImageView的)dialog.findViewById(R.id.image);
                            //image.setImageResource(R.drawable.ic_launcher);

                            按钮dialogBu​​tton =(按钮)dialog.findViewById(R.id.changebutton);
                            //如果单击按钮,关闭定制对话框
                            dialogBu​​tton.setOnClickListener(新OnClickListener(){
                                @覆盖
                                公共无效的onClick(视图v){
                                    TextView的et22 =(TextView中)dialog.findViewById(R.id.et2);
                                    numvalue = et22.getText()的toString()。
                                    FirstSSettings.setNumber(numvalue);



                      //按钮鱼缸监听器启动


                        fButton =(的ImageButton)findViewById(R.id.imageButton1);
                          //听按钮事件

                           fButton.setOnClickListener(新View.OnClickListener(){
                               布尔的WiFi,GSM;
                               字符串的x,y;
                                公共无效的onClick(查看为arg0){
                                    NUM = FirstSSettings.UserNumber;
                                    //语音
                                    MP1 = MediaPlayer.create(getBaseContext(),R.raw.menu);
                                    mp1.start();
                                    //结束语音

                                    //的String = FirstSSettings.UserGSM.toString();
                                    //串D = FirstSSettings.UserWifi.toString();
                                    //if(s.equals("false")&& d.equals(假))
                                    FirstSSettings A =新FirstSSettings();
                                尝试{Log.v(?FirstSSettings.UserGSM == NULLUserGSM是空对象:非空的对象,);
                                X = FirstSSettings.UserGSM.toString();
                                Y = FirstSSettings.UserWifi.toString();
                                }
                                赶上(例外五)
                                {
                                Log.v(抓住NullPointerException异常,错过了所有的乐趣,);
                                e.printStackTrace();
                                }
                                Log.v(X == NULLNullPointerException异常这一行后:一切都还好吧,);



                             //如果(){Y =假;}



                                如果(x.equals(假)及及(并且y.equals(假)))
                                {
                                    {

                                        最后一个对话框对话框=新的对话框(背景);
                                        dialog.setContentView(R.layout.check_dialog);
                                        dialog.setTitle(设置警报);
                                        TextView的plCheck =(TextView中)dialog.findViewById(R.id.plCheck);
                                        plCheck.setText(检查连接设置);

                                        按钮okBut =(按钮)dialog.findViewById(R.id.okBut);
                                        //临时启动

                                        //如果单击按钮,关闭定制对话框
                                    okBut.setOnClickListener(新OnClickListener(){
                                            @覆盖
                                            公共无效的onClick(视图v){
                                                dialog.dismiss();
                                                尝试
                                                {
                                                Toast.makeText(getApplicationContext(),FirstSSettings.getUserNumber(),Toast.LENGTH_SHORT).show();
                                                }
                                                赶上(例外五)
                                                {
                                                    e.printStackTrace();
                                                }
                                                意图nextScreen3 =新的意图(getApplicationContext(),FirstSSettings.class);
                                                startActivity(nextScreen3);
                                            }
                                        });

                                        dialog.show();



                                        //温度结束




                                    }

                                    其他
                                    {
                                        意图nextScreen =新的意图(getApplicationContext(),fishtank.class);
                                        startActivity(nextScreen);
                                       // Toast.makeText(getApplicationContext(),开始,Toast.LENGTH_SHORT).show();
                                        //Toast.makeText(getApplicationContext(),FirstSSettings.UserWifi.toString(),Toast.LENGTH_LONG).show();
                                        //Toast.makeText(getApplicationContext(),FirstSSettings.UserGSM.toString(),Toast.LENGTH_LONG).show();
                                        //Toast.makeText(getApplicationContext(),"End,Toast.LENGTH_SHORT).show();


                                    }


                                    //开始一个新的意图
                    / *
                     testObj =新FirstSSettings();

                                    如果(testObj.getUserGSM()==假放;&安培; testObj.getUserWifi()==假)
                                    {

                                        意图nextScreen =新的意图(getApplicationContext(),fishtank.class);
                                        startActivity(nextScreen);
                                    }
                                    其他
                                    {
                                            意图nextScreen1 =新的意图(getApplicationContext(),fishtank.class);
                                            startActivity(nextScreen1);

                                    }
                                    * /
                                }

                                             });
                        //按钮鱼缸监听结束

                           //按钮猫监听器启动

                            sButton =(的ImageButton)findViewById(R.id.imageButton2);

                              //听按钮事件
                               sButton.setOnClickListener(新View.OnClickListener(){

                                    公共无效的onClick(查看为arg0){
                                        //语音
                                        最后的MediaPlayer MP1 = MediaPlayer.create(getBaseContext(),R.raw.menu);
                                        mp1.start();
                                        //结束语音
                                        //开始一个新的意图
                                        意图nextScreen2 =新的意图(getApplicationContext(),Csoon.class);
                                        startActivity(nextScreen2);

                                    }
                                });
                            //按钮猫监听结束
                             //按钮狗监听器启动

                                TButton的=(的ImageButton)findViewById(R.id.imageButton3);

                                  //听按钮事件
                                   tButton.setOnClickListener(新View.OnClickListener(){

                                        公共无效的onClick(查看为arg0){
                                            //语音
                                            最后的MediaPlayer MP1 = MediaPlayer.create(getBaseContext(),R.raw.menu);
                                            mp1.start();
                                            //结束语音
                                            //开始一个新的意图
                                            意图nextScreen3 =新的意图(getApplicationContext(),Dsoon.class);
                                            startActivity(nextScreen3);

                                        }
                                    });}
                                //按钮狗监听结束



                    //菜单句柄
        @覆盖
        公共布尔onCreateOptionsMenu(功能菜单){
            //充气菜单;这增加了项目操作栏,如果它是present。
            。getMenuInflater()膨胀(R.menu.select_screen,菜单);
            返回true;
        }


        @覆盖
        公共布尔onOptionsItemSelected(菜单项项)
        {
              开关(item.getItemId()){
              案例R.id.C​​hangeColor:
                        //写code此选项点击后执行
                  意图nextScreen3 =新的意图(getApplicationContext(),FirstSSettings.class);
                    startActivity(nextScreen3);
                         返回true;

              案例R.id.phoneInformation:
                         //写code此选项点击后执行
                        意图nextScreen4 =新的意图(getApplicationContext(),Verify.class);
                        startActivity(nextScreen4);
                         返回true;

               案例R.id.callInfo:
                // startActivity(新的意向()setClass(MainActivity.this,LoginActivity.class).setData(getIntent()的getData())。); //写code此选项点击后执行
                                              返回true;

              案例R.id.email:
                                             //写code此选项点击后执行
                                               返回true;

                默认:
                                    返回super.onOptionsItemSelected(项目);
          }
      }



    }
 

FirstSSettings活动

 包com.set.petshome;



公共类FirstSSettings延伸活动{
按钮loginButton,saveButton,cancelButton;
//复选框gsmbox,wifibox;
公共静态布尔UserGSM;
公共静态布尔UserWifi;

公共静态字符串UserNumber;
TextView的nfield;
TextView的e_num;
复选框wifibox;
复选框gsmbox;
TextView的wifiuser,wifipass,wifi_uan,wifi_pan;
字符串wifi_u,wifi_p;

//登录变种
的EditText U,P;
TextView的资源;
字符串结果;
字符串x =移动;
螺纹runOnUiThread;
InetAddress类地址;


    公共静态无效setNumber(字符串一)
    {

        UserNumber =一个;
    }
    公布尔getUserGSM()
    {
        返回UserGSM;
    }
    公布尔getUserWifi()
    {
        返回UserWifi;
    }
    公共静态字符串getUserNumber()
    {
        返回UserNumber;
    }
    @覆盖
    保护无效的onCreate(包savedInstanceState){

        super.onCreate(savedInstanceState);

        的setContentView(R.layout.activity_first_ssettings);



        wifiuser =(TextView中)findViewById(R.id.wifiuser);
        wifi_uan =(TextView中)findViewById(R.id.wifi_uan);
        wifipass =(TextView中)findViewById(R.id.wifipass);
        wifi_pan =(TextView中)findViewById(R.id.wifi_pan);
        wifibox =(复选框)findViewById(R.id.Wifi);
        nfield =(TextView中)findViewById(R.id.ntxtfield);
        RES =(TextView中)findViewById(R.id.res);

        nfield.setText(UserNumber);


        wifibox =(复选框)findViewById(R.id.Wifi);
          //听按钮事件
        //无线CheckbBox onClickListener开始
        //温度

        wifibox.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                 如果(wifibox.isChecked())
                    {
                        的NetworkInfo xWifi;
                        ConnectivityManager connManager =(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
                        xWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        如果(xWifi.isConnected()){
                            //做什么
                        }
                        其他
                        {
                            callCheck();

                        }
                    }其他{

                    }

            }

        });

            //测试,如果它被选中或取消选中



           //无线复选框onClickListener结束
         //无线CheckbBox onCheckedChange开始
        wifibox.setOnCheckedChangeListener(新OnCheckedChangeListener()
        {
        //记录复选框的点击
        公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked)
        {


            wifiuser =(TextView中)findViewById(R.id.wifiuser);
            wifi_uan =(TextView中)findViewById(R.id.wifi_uan);
            。wifi_u = wifi_uan.getText()的toString();

            wifipass =(TextView中)findViewById(R.id.wifipass);
            wifi_pan =(TextView中)findViewById(R.id.wifi_pan);
             wifi_p = wifi_pan.getText()的toString()。
            //测试,如果它被选中或取消选中
            如果(器isChecked)
            {
                //如果是检查
                 wifiuser.setVisibility(View.VISIBLE);
                 wifi_uan.setVisibility(View.VISIBLE);
                 wifipass.setVisibility(View.VISIBLE);
                 wifi_pan.setVisibility(View.VISIBLE);
                 loginButton.setVisibility(View.VISIBLE);
                 res.setVisibility(View.VISIBLE);

            }其他{
                wifiuser.setVisibility(View.GONE);
                 wifi_uan.setVisibility(View.GONE);
                 wifipass.setVisibility(View.GONE);
                 wifi_pan.setVisibility(View.GONE);
                 loginButton.setVisibility(View.GONE);
                 res.setVisibility(View.GONE);
            }

        }
        });

        //无线复选框结束

        runOnUiThread(新的Runnable(){
              公共无效的run(){
                Toast.makeText(getApplicationContext(),你好,Toast.LENGTH_SHORT).show();
              }
            });

        // GSM CheckbBox开始

                gsmbox =(复选框)findViewById(R.id.GSM);
                gsmbox.setOnCheckedChangeListener(新OnCheckedChangeListener()
                {

                //记录复选框的点击
                公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked)
                {
                    nfield =(TextView中)findViewById(R.id.ntxtfield);
                    e_num =(TextView中)findViewById(R.id.e_num);

                    //测试,如果它被选中或取消选中
                    如果(器isChecked)
                    {
                        //如果是检查
                         nfield.setVisibility(View.VISIBLE);
                        e_num.setVisibility(View.VISIBLE);

                    }其他{
                     nfield.setVisibility(View.GONE);
                   e_num.setVisibility(View.GONE);
                    }

                }
                });

                // GSM复选框结束



        //登录按钮启动
                loginButton =(按钮)findViewById(R.id.login);

                loginButton.setOnClickListener(新OnClickListener(){

                    @覆盖
                    公共无效的onClick(视图v){
                        尝试
                        {
                        wifibox =(复选框)findViewById(R.id.Wifi);
                        gsmbox =(复选框)findViewById(R.id.GSM);

                        UserGSM = gsmbox.isChecked();
                        UserWifi = wifibox.isChecked();


                        。wifi_u = wifi_uan.getText()的toString();
                        wifi_p = wifi_pan.getText()的toString()。

                        U =(EditText上)findViewById(R.id.wifi_uan);
                        P =(EditText上)findViewById(R.id.wifi_pan);
                        Toast.makeText(getApplicationContext(),u.getText()的toString(),Toast.LENGTH_LONG。).show();
                        Toast.makeText(getApplicationContext(),p.getText()的toString(),Toast.LENGTH_LONG。).show();
                        新MyAsyncTask()执行(。u.getText()的toString(),p.getText()的toString());
                        }
                        赶上(例外五)
                        {
                            e.printStackTrace();
                        }
                    }

                });

            //登录按钮结束



        //保存按钮启动
        saveButton =(按钮)findViewById(R.id.save);
        //温度OBJ

        saveButton.setOnClickListener(新OnClickListener(){
             公共无效的onClick(查看为arg0){
                 nfield =(TextView中)findViewById(R.id.ntxtfield);
                 // wifibox =(复选框)findViewById(R.id.Wifi);
                 // gsmbox =(复选框)findViewById(R.id.GSM);

                 setNumber(nfield.getText()的toString());
                    //UserGSM=gsmbox.isChecked();
                    //UserWifi=wifibox.isChecked();


                    //开始一个新的意图
                    //wifi_u=wifi_uan.getText()的toString()。

                    //wifi_p=wifi_pan.getText()的toString()。

                    意图nextScreen =新的意图(getApplicationContext(),SelectPetsScreen.class);
                    startActivity(nextScreen);

                    //使用setdefaults();

                尝试
                {
                    Toast.makeText(getApplicationContext(),UserNumber,Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(),UserGSM.toString(),Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(),UserWifi.toString(),Toast.LENGTH_SHORT).show();
                }
                赶上(例外五)
                {
                    e.printStackTrace();
                }



                }

            });


        //保存按钮结束



        //取消按钮启动
      cancelButton =(按钮)findViewById(R.id.cancel);
        cancelButton.setOnClickListener(新OnClickListener(){
             公共无效的onClick(查看为arg0){

                    //开始一个新的意图
                    意图nextScreen2 =新的意图(getApplicationContext(),SelectPetsScreen.class);
                    startActivity(nextScreen2);

                }
            });

        //取消按钮结束

    }


}
 

logcat的

  12-04 21:04:05.041:E / AndroidRuntime(2789):致命异常:主要
12-04 21:04:05.041:E / AndroidRuntime(2789):显示java.lang.NullPointerException
12-04 21:04:05.041:E / AndroidRuntime(2789):在com.set.petshome.SelectPetsScreen $ 4.onClick(SelectPetsScreen.java:211)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.view.View.performClick(View.java:4240)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.view.View $ PerformClick.run(View.java:17721)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.os.Handler.handleCallback(Handler.java:730)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.os.Handler.dispatchMessage(Handler.java:92)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.os.Looper.loop(Looper.java:137)
12-04 21:04:05.041:E / AndroidRuntime(2789):在android.app.ActivityThread.main(ActivityThread.java:5103)
12-04 21:04:05.041:E / AndroidRuntime(2789):在java.lang.reflect.Method.invokeNative(本机方法)
12-04 21:04:05.041:E / AndroidRuntime(2789):在java.lang.reflect.Method.invoke(Method.java:525)
12-04 21:04:05.041:E / AndroidRuntime(2789):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
12-04 21:04:05.041:E / AndroidRuntime(2789):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-04 21:04:05.041:E / AndroidRuntime(2789):在dalvik.system.NativeStart.main(本机方法)
 

解决方案

 公共静态布尔UserGSM; //它的对象不是原始的,所以默认情况下它是空
公共静态布尔UserWifi; //同样的事情
 

此变量可以永远不会初始化,并持有空。因此,x和y是空的,因为FirstSSettings.UserGSM.toString()被逮住在try块的NullPointerException异常和叶x等于为null。

试试这个:

  ...
FirstSSettings A =新FirstSSettings();
尝试 {
    Log.v(?FirstSettings.UserGSM == NULLUserGSM是空对象:非空对象);
    X = FirstSSettings.UserGSM.toString();
    Y = FirstSSettings.UserWifi.toString();
}赶上(例外五){
    Log.v(抓住NullPointerException异常,错过了所有的乐趣);
    e.printStackTrace();
}
Log.v(X == NULLNullPointerException异常这一行后:一切都还好吧);
如果(x.equals(假)及及(并且y.equals(假)))
...
 

要prevent NullPointerException异常只是初始化布尔

  ...
公共类FirstSSettings延伸活动{
按钮loginButton,saveButton,cancelButton;
//复选框gsmbox,wifibox;
公共静态布尔UserGSM = FALSE; //或真根据您的需求
公共静态布尔UserWifi = FALSE; //或真根据您的需求
...
 

My Android application keeps crashing when i click on Fish option and nothing is inserted in the settings activity it's a null pointer exception and i tried to handle it but no result so here is my codeSelectPetsScreen Acivity

package com.set.petshome;
public class SelectPetsScreen extends Activity  {
    fishtank ii=new fishtank();
    ImageButton fButton,sButton,tButton;
    Button chButton,setsButton;
      private MediaPlayer mp0,mp1;
      public String value;
      final Context context = this;
      String numvalue;
    FirstSSettings testObj= new FirstSSettings();
        //public String chnumber;// recipient's mobile number
        public String num;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectscreen);
                    //menu startup sound Code
      mp0=MediaPlayer.create(this,R.raw.menu);
        mp0.start();

        //End Menu Sound Code

        //Settings Button Start
        setsButton = (Button) findViewById(R.id.settingsb);
        setsButton.setOnClickListener(new OnClickListener() {
             public void onClick(View arg0) {
                    //Voice
                    mp1=MediaPlayer.create(getBaseContext(),R.raw.menu);
                    mp1.start();
                    //End Voice
                    //Starting a new Intent

                    Intent nextScreen = new Intent(getApplicationContext(), FirstSSettings.class);
                    startActivity(nextScreen);

                }
            });

        //Settings Button End


        //Second Ch No.Button Start
            chButton = (Button) findViewById(R.id.changebutton);
            // add button listener
                    chButton.setOnClickListener(new OnClickListener() {


                        @Override
                        public void onClick(View arg0) {

                            // custom dialog
                            final Dialog dialog = new Dialog(context);
                            dialog.setContentView(R.layout.mycustom);
                            dialog.setTitle("Change Number");

                            // set the custom dialog components - text, image and button
                            TextView current = (TextView) dialog.findViewById(R.id.cn);
                            current.setText("Current Number:");
                        //current.setText("Current Number:");
                        TextView et11 = (TextView) dialog.findViewById(R.id.et1);
                        //et11.setKeyListener(null);

                        et11.setText(FirstSSettings.getUserNumber());

                        TextView newnum = (TextView) dialog.findViewById(R.id.nn);
                        newnum.setText("New Number:");
                        TextView et22 = (TextView) dialog.findViewById(R.id.et2);
                        et22.setText("");






                        //  ImageView image = (ImageView) dialog.findViewById(R.id.image);
                            //image.setImageResource(R.drawable.ic_launcher);

                            Button dialogButton = (Button) dialog.findViewById(R.id.changebutton);
                            // if button is clicked, close the custom dialog
                            dialogButton.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    TextView et22 = (TextView) dialog.findViewById(R.id.et2);
                                    numvalue = et22.getText().toString();
                                    FirstSSettings.setNumber(numvalue);



                      //Button Fishtank Listener Start


                        fButton = (ImageButton) findViewById(R.id.imageButton1);
                          //Listening to button event

                           fButton.setOnClickListener(new View.OnClickListener() {
                               Boolean wifi,gsm;
                               String x,y;
                                public void onClick(View arg0) {
                                    num=FirstSSettings.UserNumber;
                                    //Voice
                                    mp1=MediaPlayer.create(getBaseContext(),R.raw.menu);
                                    mp1.start();
                                    //End Voice

                                    //String s = FirstSSettings.UserGSM.toString();
                                    //String d = FirstSSettings.UserWifi.toString();
                                    //if(s.equals("false")&& d.equals("false"))
                                    FirstSSettings a=new FirstSSettings();
                                try { Log.v(FirstSSettings.UserGSM == null ? "UserGSM is Null object": "Not Null object", "");
                                x=FirstSSettings.UserGSM.toString();
                                y=FirstSSettings.UserWifi.toString();
                                }
                                catch(Exception e)
                                {
                                Log.v("Catch NullPointerException and missed all the fun","");
                                e.printStackTrace();
                                }
                                Log.v(x == null ? "NullPointerException after this line": "Everything is allright","");



                             //  if();{y="false";}



                                if(x.equals("false")&&(y.equals("false")))
                                {
                                    {

                                        final Dialog dialog = new Dialog(context);
                                        dialog.setContentView(R.layout.check_dialog);
                                        dialog.setTitle("Settings Alert");
                                        TextView plCheck = (TextView) dialog.findViewById(R.id.plCheck);
                                        plCheck.setText("Check Your Connection Settings");

                                        Button okBut = (Button) dialog.findViewById(R.id.okBut);
                                        //Temp Start

                                        // if button is clicked, close the custom dialog
                                    okBut.setOnClickListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                                try
                                                {
                                                Toast.makeText(getApplicationContext(), FirstSSettings.getUserNumber(), Toast.LENGTH_SHORT).show();
                                                }
                                                catch (Exception e)
                                                {
                                                    e.printStackTrace();
                                                }
                                                Intent nextScreen3 = new Intent(getApplicationContext(), FirstSSettings.class);
                                                startActivity(nextScreen3);
                                            }
                                        });

                                        dialog.show();



                                        //Temp End




                                    }

                                    else
                                    {
                                        Intent nextScreen = new Intent(getApplicationContext(), fishtank.class);
                                        startActivity(nextScreen);
                                       // Toast.makeText(getApplicationContext(), "Start", Toast.LENGTH_SHORT).show();
                                        //Toast.makeText(getApplicationContext(), FirstSSettings.UserWifi.toString(), Toast.LENGTH_LONG).show();
                                        //Toast.makeText(getApplicationContext(), FirstSSettings.UserGSM.toString(), Toast.LENGTH_LONG).show();
                                        //Toast.makeText(getApplicationContext(),"End", Toast.LENGTH_SHORT).show();


                                    }


                                    //Starting a new Intent
                    /*
                     testObj =new FirstSSettings();

                                    if(testObj.getUserGSM()==false&&testObj.getUserWifi()==false)
                                    {

                                        Intent nextScreen = new Intent(getApplicationContext(), fishtank.class);
                                        startActivity(nextScreen);
                                    }
                                    else
                                    {
                                            Intent nextScreen1 = new Intent(getApplicationContext(), fishtank.class);
                                            startActivity(nextScreen1);

                                    }
                                    */
                                }

                                             });
                        //Button Fishtank Listener End

                           //Button Cats Listener Start

                            sButton = (ImageButton) findViewById(R.id.imageButton2);

                              //Listening to button event
                               sButton.setOnClickListener(new View.OnClickListener() {

                                    public void onClick(View arg0) {
                                        //Voice
                                        final MediaPlayer mp1=MediaPlayer.create(getBaseContext(),R.raw.menu);
                                        mp1.start();
                                        //End Voice
                                        //Starting a new Intent
                                        Intent nextScreen2 = new Intent(getApplicationContext(), Csoon.class);
                                        startActivity(nextScreen2);

                                    }
                                });
                            //Button Cats Listener End
                             //Button Dogs Listener Start

                                tButton = (ImageButton) findViewById(R.id.imageButton3);

                                  //Listening to button event
                                   tButton.setOnClickListener(new View.OnClickListener() {

                                        public void onClick(View arg0) {
                                            //Voice
                                            final MediaPlayer mp1=MediaPlayer.create(getBaseContext(),R.raw.menu);
                                            mp1.start();
                                            //End Voice
                                            //Starting a new Intent
                                            Intent nextScreen3 = new Intent(getApplicationContext(), Dsoon.class);
                                            startActivity(nextScreen3);

                                        }
                                    });}
                                //Button Dogs Listener End



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


        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {
              switch (item.getItemId()) {
              case R.id.ChangeColor:
                        // write code to execute when clicked on this option
                  Intent nextScreen3 = new Intent(getApplicationContext(), FirstSSettings.class);
                    startActivity(nextScreen3);
                         return true;

              case R.id.phoneInformation:
                         // write code to execute when clicked on this option
                        Intent nextScreen4 = new Intent(getApplicationContext(), Verify.class);
                        startActivity(nextScreen4);
                         return true;

               case R.id.callInfo:
                //   startActivity(new Intent().setClass(MainActivity.this, LoginActivity.class).setData(getIntent().getData()));                        // write code to execute when clicked on this option
                                              return true;

              case R.id.email:
                                             // write code to execute when clicked on this option
                                               return true;

                default:
                                    return super.onOptionsItemSelected(item);
          }
      }



    }

FirstSSettings Activity

package com.set.petshome;



public class FirstSSettings extends Activity {
Button loginButton,saveButton,cancelButton;
//CheckBox gsmbox,wifibox;
public static  Boolean UserGSM;
public  static Boolean UserWifi;

public  static String UserNumber;
TextView nfield ;
TextView e_num;
CheckBox wifibox;
CheckBox gsmbox ;
TextView wifiuser,wifipass,wifi_uan,wifi_pan;
String wifi_u,wifi_p;

//login var
EditText u,p;
TextView res;
String result;
String x="mobile";
Thread runOnUiThread;
InetAddress address;


    public  static void setNumber(String a)
    {

        UserNumber=a;
    }
    public Boolean getUserGSM()
    {
        return UserGSM;
    }
    public Boolean getUserWifi()
    {
        return UserWifi;
    }
    public static String getUserNumber()
    {
        return UserNumber;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first_ssettings);



        wifiuser = (TextView) findViewById(R.id.wifiuser);
        wifi_uan = (TextView) findViewById(R.id.wifi_uan);
        wifipass=(TextView) findViewById(R.id.wifipass);
        wifi_pan = (TextView) findViewById(R.id.wifi_pan);
        wifibox= (CheckBox) findViewById(R.id.Wifi);
        nfield = (TextView) findViewById(R.id.ntxtfield);
        res=(TextView)findViewById(R.id.res);

        nfield.setText(UserNumber);


        wifibox = (CheckBox) findViewById(R.id.Wifi);
          //Listening to button event
        //Wifi CheckbBox onClickListener start
        //Temp

        wifibox.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                 if (wifibox.isChecked())
                    {
                        NetworkInfo xWifi;
                        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                        xWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        if (xWifi.isConnected()) {
                            // Do whatever
                        }
                        else
                        {
                            callCheck();

                        }
                    }else{

                    }

            }

        });

            //testing if it is checked or unchecked



           //Wifi Checkbox onClickListener end
         //Wifi CheckbBox onCheckedChange start
        wifibox.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
        //recording the click of the checkbox
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {


            wifiuser = (TextView) findViewById(R.id.wifiuser);
            wifi_uan = (TextView) findViewById(R.id.wifi_uan);
            wifi_u=wifi_uan.getText().toString();

            wifipass=(TextView) findViewById(R.id.wifipass);
            wifi_pan = (TextView) findViewById(R.id.wifi_pan);
             wifi_p=wifi_pan.getText().toString();
            //testing if it is checked or unchecked
            if ( isChecked )
            {
                //if it is check
                 wifiuser.setVisibility(View.VISIBLE);
                 wifi_uan.setVisibility(View.VISIBLE);
                 wifipass.setVisibility(View.VISIBLE);
                 wifi_pan.setVisibility(View.VISIBLE);
                 loginButton.setVisibility(View.VISIBLE);
                 res.setVisibility(View.VISIBLE);

            }else{
                wifiuser.setVisibility(View.GONE);
                 wifi_uan.setVisibility(View.GONE);
                 wifipass.setVisibility(View.GONE);
                 wifi_pan.setVisibility(View.GONE);
                 loginButton.setVisibility(View.GONE);
                 res.setVisibility(View.GONE);
            }

        }
        });

        //Wifi CheckBox end

        runOnUiThread(new Runnable() {
              public void run() {
                Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
              }
            });

        //GSM CheckbBox start

                gsmbox = (CheckBox) findViewById(R.id.GSM);
                gsmbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
                {

                //recording the click of the checkbox
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    nfield = (TextView) findViewById(R.id.ntxtfield);
                    e_num=(TextView) findViewById(R.id.e_num);

                    //testing if it is checked or unchecked
                    if ( isChecked )
                    {
                        //if it is check
                         nfield.setVisibility(View.VISIBLE);
                        e_num.setVisibility(View.VISIBLE);

                    }else{
                     nfield.setVisibility(View.GONE);
                   e_num.setVisibility(View.GONE);
                    }

                }
                });

                //GSM CheckBox end



        //login Button start
                loginButton = (Button) findViewById(R.id.login);

                loginButton.setOnClickListener(new OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        try
                        {
                        wifibox= (CheckBox) findViewById(R.id.Wifi);
                        gsmbox = (CheckBox) findViewById(R.id.GSM);

                        UserGSM=gsmbox.isChecked();
                        UserWifi=wifibox.isChecked();


                        wifi_u=wifi_uan.getText().toString();
                        wifi_p=wifi_pan.getText().toString();

                        u = (EditText) findViewById(R.id.wifi_uan);
                        p = (EditText) findViewById(R.id.wifi_pan);
                        Toast.makeText(getApplicationContext(), u.getText().toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getApplicationContext(), p.getText().toString(), Toast.LENGTH_LONG).show();
                        new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                    }

                });

            //login Button end



        //Save Button Start
        saveButton = (Button) findViewById(R.id.save);
        //Temp obj

        saveButton.setOnClickListener(new OnClickListener() {
             public void onClick(View arg0) {
                 nfield = (TextView) findViewById(R.id.ntxtfield);
                 //wifibox= (CheckBox) findViewById(R.id.Wifi);
                 //gsmbox = (CheckBox) findViewById(R.id.GSM);

                 setNumber(nfield.getText().toString());
                    //UserGSM=gsmbox.isChecked();
                    //UserWifi=wifibox.isChecked();


                    //Starting a new Intent
                    //wifi_u=wifi_uan.getText().toString();

                    //wifi_p=wifi_pan.getText().toString();

                    Intent nextScreen = new Intent(getApplicationContext(), SelectPetsScreen.class);
                    startActivity(nextScreen);

                    //setDefaults();

                try
                {
                    Toast.makeText(getApplicationContext(), UserNumber, Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), UserGSM.toString(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), UserWifi.toString(), Toast.LENGTH_SHORT).show();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }



                }

            });


        //Save button End



        //Cancel button Start
      cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new OnClickListener() {
             public void onClick(View arg0) {

                    //Starting a new Intent
                    Intent nextScreen2 = new Intent(getApplicationContext(), SelectPetsScreen.class);
                    startActivity(nextScreen2);

                }
            });

        //Cancel Button End

    }


}

Logcat

    12-04 21:04:05.041: E/AndroidRuntime(2789): FATAL EXCEPTION: main
12-04 21:04:05.041: E/AndroidRuntime(2789): java.lang.NullPointerException
12-04 21:04:05.041: E/AndroidRuntime(2789):     at com.set.petshome.SelectPetsScreen$4.onClick(SelectPetsScreen.java:211)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.view.View.performClick(View.java:4240)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.view.View$PerformClick.run(View.java:17721)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.os.Handler.handleCallback(Handler.java:730)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.os.Looper.loop(Looper.java:137)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at java.lang.reflect.Method.invokeNative(Native Method)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at java.lang.reflect.Method.invoke(Method.java:525)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-04 21:04:05.041: E/AndroidRuntime(2789):     at dalvik.system.NativeStart.main(Native Method)
解决方案
public static  Boolean UserGSM;// its an Object not primitive, so by default it is null
public  static Boolean UserWifi;//same thing

This variables can be never initialized and holds null. So x and y are null, because FirstSSettings.UserGSM.toString() are catched in try block as NullPointerException and leaves x equals to null.

Try this:

...
FirstSSettings a=new FirstSSettings();
try {
    Log.v(FirstSettings.UserGSM == null ? "UserGSM is Null object": "Not Null object");
    x=FirstSSettings.UserGSM.toString();
    y=FirstSSettings.UserWifi.toString();
} catch(Exception e) {
    Log.v("Catch NullPointerException and missed all the fun");
    e.printStackTrace();
}
Log.v(x == null ? "NullPointerException after this line": "Everything is allright");
if(x.equals("false")&&(y.equals("false")))
...

To prevent NullPointerException just initialize Booleans

...
public class FirstSSettings extends Activity {
Button loginButton,saveButton,cancelButton;
//CheckBox gsmbox,wifibox;
public static  Boolean UserGSM = false;// or true based on your needs
public  static Boolean UserWifi = false;// or true based on your needs
...

这篇关于Android的NullPointerException异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:52