尝试在空对象引用上调用虚拟方法“java.lang.Object android.content.Context.getSystemService(java.lang.String)”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30416991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:35:39  来源:igfitidea点击:

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

javaandroidnullpointerexception

提问by

I am trying to check if my application is launched for the first time. If yes, the user is asked for an input. Then, check if Wi-Fi is connected. If Wi-Fi is connected, I use the input provides by the user to load a WebView.

我正在尝试检查我的应用程序是否是第一次启动。如果是,则要求用户输入。然后,检查 Wi-Fi 是否已连接。如果连接了 Wi-Fi,我会使用用户提供的输入来加载 WebView。

But, the app crashes on launch with an error

但是,该应用程序在启动时崩溃并出现错误

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

尝试在空对象引用上调用虚拟方法“java.lang.Object android.content.Context.getSystemService(java.lang.String)”

Code

代码

public class MainActivity extends Activity {


ProgressBar progressbar;
WebView webView;
LayoutInflater li = LayoutInflater.from(getBaseContext());
View promptsView = li.inflate(R.layout.propmt, null);
String URL;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.activity_main);

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getBoolean("isFirstRun", true);

    if (isFirstRun) {

        otherWork(promptsView);

    }


       getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
                .putBoolean("isFirstRun", false).commit();





    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi.isConnected()) {


    getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

    webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setRenderPriority(RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    if (Build.VERSION.SDK_INT >= 19) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }       
    else {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    webView.loadUrl(URL);
    webView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);



       webView.setWebViewClient(new MyWebViewClient());

       progressbar=(ProgressBar)findViewById(R.id.progressBar); 

       webView.setWebChromeClient(new WebChromeClient() {

       // this will be called on page loading progress

       @Override

       public void onProgressChanged(WebView view, int newProgress) {

               super.onProgressChanged(view, newProgress);


               progressbar.setProgress(newProgress);
               //loadingTitle.setProgress(newProgress);
               // hide the progress bar if the loading is complete

               if (newProgress == 100) {
               progressbar.setVisibility(View.GONE);

               } else{
               progressbar.setVisibility(View.VISIBLE);

               }

               }

            });

       } else {

           AlertDialog.Builder AD = new AlertDialog.Builder(this);
            AD.setIcon(R.drawable.ic_launcher);
            AD.setTitle("Not Connected To Wi-Fi/WLAN");
            AD.setMessage("You need an Active Wi-Fi/WLAN on Alliance Broadband Network");
            AD.setPositiveButton(android.R.string.ok, new OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    finish();

                }
            });
            AD.show();

       }


} 

public void otherWork(View promptsView) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            this);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView
            .findViewById(R.id.editTextDialogUserInput);

    // set dialog message
    alertDialogBuilder
    .setCancelable(false)
    .setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            // get user input and set it to result
            // edit text
            //result.setText(userInput.getText());
            SharedPreferences pos;
            String fileName = "file";

            pos = getSharedPreferences(fileName, 0);
            SharedPreferences.Editor editor = pos.edit();
            editor.putString("pwd", userInput.getText().toString());      
            editor.commit();

            pos = getSharedPreferences(fileName, 0);
            String data = pos.getString("pwd", "");


            URL = data.toString();

        }
    })
    .setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            dialog.cancel();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}


       @Override
       public boolean onKeyDown(int keyCode, KeyEvent event) {

       if(keyCode == KeyEvent.KEYCODE_BACK){
           finish();
         }
       return super.onKeyDown(keyCode, event);
       }

       private class MyWebViewClient extends WebViewClient {


     @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) {

     view.loadUrl(url);
     return true;
     }
     }<br>

LogCat

日志猫

05-24 01:11:19.279: E/AndroidRuntime(3719): FATAL EXCEPTION: main
05-24 01:11:19.279: E/AndroidRuntime(3719): Process: com.mavenmaverick.ipconnect, PID: 3719
05-24 01:11:19.279: E/AndroidRuntime(3719): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mavenmaverick.ipconnect/com.mavenmaverick.ipconnect.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread.access0(ActivityThread.java:144)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.os.Looper.loop(Looper.java:135)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread.main(ActivityThread.java:5221)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at java.lang.reflect.Method.invoke(Native Method)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at java.lang.reflect.Method.invoke(Method.java:372)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 01:11:19.279: E/AndroidRuntime(3719): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.view.LayoutInflater.from(LayoutInflater.java:219)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at com.mavenmaverick.ipconnect.MainActivity.<init>(MainActivity.java:47)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at java.lang.reflect.Constructor.newInstance(Native Method)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at java.lang.Class.newInstance(Class.java:1572)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
05-24 01:11:19.279: E/AndroidRuntime(3719):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
05-24 01:11:19.279: E/AndroidRuntime(3719):     ... 10 more

回答by CommonsWare

LayoutInflater li = LayoutInflater.from(getBaseContext());

LayoutInflater li = LayoutInflater.from(getBaseContext());

First, you do not need getBaseContext(), nor do you need LayoutInflater.from(). Use getLayoutInflater().

首先,你不需要getBaseContext(),也不需要LayoutInflater.from()。使用getLayoutInflater().

Second, you cannot call methods on the Activitysuperclass until after super.onCreate(), except in certain situations. Please postpone your initialization of promptsViewuntil after super.onCreate()has been called.

其次,除非在某些情况下,否则在Activityafter 之前不能调用超类上的方法super.onCreate()。请将您的初始化推迟promptsViewsuper.onCreate()被调用之后。

回答by himanshu jain

View view = inflater.inflate(R.layout.fragment_name, container, false);
view.getContext();

Use view.getContext()wherever you need Application Context in fragments.

view.getContext()在您需要片段中的应用程序上下文的任何地方使用。