代码之家  ›  专栏  ›  技术社区  ›  Nilesh Gajare

无法启动活动ComponentInfo:java.lang.NullPointerException

  •  0
  • Nilesh Gajare  · 技术社区  · 9 年前

    我已经搜索了这个错误并找到了许多解决方案,但我无法解决这个问题,因为我是Android初学者

    这是我的主要活动

    package ***.***.greytrix.test;
    
    import android.app.LauncherActivity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.os.AsyncTask;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    
    import android.widget.TextView;
    
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesUtil;
    import com.google.android.gms.gcm.GoogleCloudMessaging;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    
    import android.webkit.CookieManager;
    
    public class MainActivity extends ActionBarActivity {
    
    
        private WebView mWebView;
        private  Context context;
    
        public static final String EXTRA_MESSAGE = "message";
        public static final String PROPERTY_REG_ID = "registration_id";
        private static final String PROPERTY_APP_VERSION = "appVersion";
        private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
        // please enter your sender id
        String SENDER_ID = "11111111";
    
        static final String TAG = "Pocket ";
        GoogleCloudMessaging gcm;
    
        TextView mDisplay;
    
        String regid;
        String fileurl="https://neel.test.com/";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
    
            setContentView(R.layout.activity_main);
            context = getApplicationContext();
    
            if(checkPlayServices()){
                gcm = GoogleCloudMessaging.getInstance(this);
               regid = getRegistrationId(context);
    
    
                //For Testing Purpose
                  new RegisterBackground().execute();
            }
    
    
            Bundle extras = getIntent().getExtras();
            String url;
    
            if (extras != null) {
    
                url = extras.getString("url");
    
                mWebView = (WebView) findViewById(R.id.activity_main_webview);
    
                mWebView.getSettings().setJavaScriptEnabled(true);
                mWebView.getSettings().setDomStorageEnabled(true);
                mWebView.getSettings().setDatabaseEnabled(true);
    
                if (extras.getString("url").isEmpty()) {
                    mWebView.loadUrl("https://neel.test.com/");
                } else {
                    mWebView.loadUrl(url);
                }
                mWebView.setWebViewClient(new MyAppWebViewClient());
    
            } else {
    
                mWebView = (WebView) findViewById(R.id.activity_main_webview);
    
                WebSettings webSettings = mWebView.getSettings();
                webSettings.setJavaScriptEnabled(true);
                webSettings.setDomStorageEnabled(true);
                webSettings.setDatabaseEnabled(true);
    
                 fileurl = ReadFile();
    
                if (fileurl == "") {
                    fileurl="https://neel.test.com/";
                    mWebView.loadUrl("https://neel.test.com/");
                } else {
                    mWebView.loadUrl(fileurl);
                }
                mWebView.setWebViewClient(new MyAppWebViewClient());
    
            }
    
        }
    
        private String ReadFile() {
    
            String aBuffer = "";
    
            try {
                File myFile = new File(getFilesDir() + "/mysdfile.txt");
                if (myFile.exists()) {
                    FileInputStream fIn = new FileInputStream(myFile);
                    BufferedReader myReader = new BufferedReader(
                            new InputStreamReader(fIn));
                    String aDataRow = "";
    
                    while ((aDataRow = myReader.readLine()) != null) {
                        aBuffer += aDataRow + "\n";
                    }
                    myReader.close();
                }
    
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
    
            return aBuffer.trim();
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.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.SetURL) {
    
                Intent nextscreen = new Intent(PayrollApplication.getContext(), SecondScreenActivity.class);
                startActivity(nextscreen);
    
                //setContentView(R.layout.seturl);
    
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        @Override
        public void onBackPressed() {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                super.onBackPressed();
            }
        }
        @Override
        protected void onResume(){
            super.onResume();
            checkPlayServices();
        }
    
        //New Code developed by Nilesh Gajare on 10th July 2015
    
        class RegisterBackground extends AsyncTask<String,String,String> {
    
            @Override
            protected String doInBackground(String... arg0) {
                // TODO Auto-generated method stub
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    msg = "Device registered, registration ID=" + regid;
                    Log.d("111", msg);
                    sendRegistrationIdToBackend();
    
                    // Persist the regID - no need to register again.
                   storeRegistrationId(context, regid);
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                }
                return msg;
            }
    
            @Override
            protected void onPostExecute(String msg) {
                //mDisplay.append(msg + "\n");
    
            }
            private void sendRegistrationIdToBackend() {
                // Set Server URL for Storing Android Device Registration ID.
    
                String CompanyCode= getCookie(fileurl,"CompanyId");
                String UserName= getCookie(fileurl,"UserName");
                String Password= getCookie(fileurl,"Password");
    
                String url = "https://neel.test.com//api/v1.0/SaveAndroidRegId?RegId="+regid+"&CompanyId="+CompanyCode+"&UserName="+UserName+"&Password="+Password ;   
    
                try {
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                   Log.i(TAG,httpResponse.getStatusLine().toString());
                    Log.i(TAG,httpResponse.getEntity().toString());
    
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
    
            }
    
            private void storeRegistrationId(Context context, String regId) {
                final SharedPreferences prefs = getGCMPreferences(context);
                int appVersion = getAppVersion(context);
                Log.i(TAG, "Saving regId on app version " + appVersion);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(PROPERTY_REG_ID, regId);
                editor.putInt(PROPERTY_APP_VERSION, appVersion);
                editor.commit();
            }
        }
    
        private boolean checkPlayServices() {
            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.SUCCESS) {
                if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                    GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                            PLAY_SERVICES_RESOLUTION_REQUEST).show();
                } else {
                    Log.i(TAG, "This device is not supported.");
                    finish();
                }
                return false;
            }
            return true;
        }
        private String getRegistrationId(Context context) {
            final SharedPreferences prefs = getGCMPreferences(context);
    
            String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    
    
            if (registrationId.isEmpty()) {
                Log.i(TAG, "Registration not found.");
                return "";
            }
    
            int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
            int currentVersion = getAppVersion(context);
            if (registeredVersion != currentVersion) {
                Log.i(TAG, "App version changed.");
                return "";
            }
            return registrationId;
        }
    
        private SharedPreferences getGCMPreferences(Context context) {
    
            return getSharedPreferences(MainActivity.class.getSimpleName(),
                    Context.MODE_PRIVATE);
        }
    
        private static int getAppVersion(Context context) {
            try {
                PackageInfo packageInfo = context.getPackageManager()
                        .getPackageInfo(context.getPackageName(), 0);
                return packageInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                // should never happen
                throw new RuntimeException("Could not get package name: " + e);
            }
        }
    
        public String getCookie(String siteName,String CookieName){
            String CookieValue = null;
    
            CookieManager cookieManager = CookieManager.getInstance();
            String cookies = cookieManager.getCookie(siteName);
            if(cookies != null) {
                String[] temp = cookies.split(";");
                for (String ar1 : temp) {
                    if (ar1.contains(CookieName)) {
                        String[] temp1 = ar1.split("=");
                        CookieValue = temp1[1];
                    }
                }
            }
            return CookieValue;
        }
    
    
    }
    

    在MainActivy。xml,我得到了以下代码:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:context=".MainActivity">
    
    
    
        <WebView
            android:id="@+id/activity_main_webview"
            android:layout_width="fill_parent"
            android:layout_height= "fill_parent"
            android:layout_weight="1.0" />
    
    </RelativeLayout>
    

    堆栈跟踪为

    流程:com.pockethcm.xxx。测试,PID:2347 java.lang.RuntimeException:无法启动活动ComponentInfo{xxx.xxx.xxx.test/xxx.xxx.test.MainActivity}: java.lang.NullPointerException:尝试调用虚拟方法 '布尔java.lang.String。空对象引用上的isEmpty()' 在android.app.ActivityThread.propertyLaunchActivity(ActivityThread.java:2298) 位于android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access$800(ActivityThread.java:144) 位于android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.lop(Looper.java:135) 位于android.app.ActivityThread.main(ActivityThread.java:5221) 位于java.lang.reflect.Method。invoke(本机方法) 位于java.lang.reflect.Method.invoke(Method.java:372) 位于com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 原因:java.lang.NullPointerException:尝试调用虚拟方法“boolean java.lang.String”。空对象上的isEmpty()' 参考 在selfservice.pockhcm.greytrix.test.MainActivity.onCreate(MainActivity.java:106) 位于android.app.Activity.performCreate(Activity.java:5937) 位于android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 在android.app.ActivityThread.productLaunchActivity(ActivityThread.java:2251) 位于android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access$800(ActivityThread.java:144) 位于android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.lop(Looper.java:135) 位于android.app.ActivityThread.main(ActivityThread.java:5221) 位于java.lang.reflect.Method。invoke(本机方法) 位于java.lang.reflect.Method.invoke(Method.java:372) 位于com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 在com.android.internal.os.ZygoteInit.main(ZygoteIndit.java:694)设备上 脱机

    清单在下面

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="selfservice.xxx.xxx.test"
        android:versionCode="2"
        android:versionName="1.1">
    
        <uses-sdk
            android:minSdkVersion="16"
            android:targetSdkVersion="17" />
    
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
        <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
    
        <permission
            android:name="selfservice.xxx.xxx.test.permission.C2D_MESSAGE"
            android:protectionLevel="signature" />
    
        <uses-permission android:name="selfservice.xxx.xxx.test.gcm.permission.C2D_MESSAGE" />
    
        <application
            android:name="selfservice.xxx.xxx.test.PayrollApplication"
            android:allowBackup="true"
            android:icon="@mipmap/icon_pocket"
            android:label="Pocket HCM"
            android:theme="@style/AppTheme">
            <activity
                android:name="selfservice.xxx.xxx.test.MainActivity"
                android:label="Pocket HCM"
                android:screenOrientation="portrait" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="selfservice.xxx.xxx.test.SecondScreenActivity"
                android:screenOrientation="portrait"></activity>
    
    
            <receiver
                android:name="selfservice.xxx.xxx.test.GcmBroadcastReceiver"
                android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
    
                    <!-- Receives the actual messages. -->
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    
                    <category android:name="selfservice.xxx.xxx.test" />
                </intent-filter>
            </receiver>
    
            <service android:name="selfservice.xxx.xxx.test.GcmIntentService" />
    
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />
    
            <activity
                android:name="selfservice.pockethcm.greytrix.test.ReceiveActivity">
            </activity>   
    
        </application>
    
    </manifest>
    

    它在安装应用程序后首次运行,但当我们关闭并重新打开时,它崩溃了 很遗憾,应用程序已关闭 你有什么想法吗,非常感谢:)

    谢谢

    1 回复  |  直到 9 年前
        1
  •  1
  •   Sharp Edge    9 年前

    这是你投掷NPE的罪魁祸首:

    if (extras.getString("url").isEmpty()) {
    

    如果 url null 是否:

    url = extras.getString("url");
    if(url == null){
    Log.d("url status","its null");
    }