-1

...我已經尋找這個錯誤,並發現了許多解決方案,但我不能夠解決問題,因爲在我的Android無法啓動活動ComponentInfo:顯示java.lang.NullPointerException

這裏是初學者是我的主要活動

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.test,PID:2347 了java.lang.RuntimeException:無法啓動活動ComponentInfo {xxx.xxx.xxx.test/xxx.xxx.xxx.test.MainActivity}: java.lang.NullPointerException:嘗試調用虛擬方法 'boolean java.lang.String.isEmpty()'null對象引用 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) at android.app .ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access $ 800(ActivityThread.java:144) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278) 的機器人。 os.Handler.dispatchMessage(手在android.app.ActivityThread.main(ActivityThread.java:5221)處使用android.os.Looper.loop(Looper.java:135) (在java.lang.reflect.Method.invoke處使用 )本地方法) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal .os.ZygoteInit.main(ZygoteInit.java:694) 引起:java.lang.NullPointerException:試圖在空對象 參考 自助服務調用虛擬方法'布爾java.lang.String.isEmpty()'。 pokethcm.greytrix.test.MainActivity.onCreate(MainActivity.java:106) at android.app.Activity.performCreate(Activity.java:5937) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 在android.app.ActivityThread.access $ 800(ActivityThread.java:144) at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang方法.invoke(本地方法) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit。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> 

它正在爲第一次安裝應用程序後,但是當我們關閉並重新打開它崩潰不幸的是應用程序已經關閉 你有什麼想法,這將不勝感激:)

謝謝!

+0

作爲日誌'String.isEmpty()上的」空對象引用...' –

+0

哪一行是#106? if(extras.getString(「url」)。isEmpty()){ –

+0

檢查'registrationId!= null'在檢查'registrationId.isEmpty()' – Rustam

回答

1

這是NPE您元兇會拋出:

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

你應該做一個檢查這裏如果urlnull與否:

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

它的作品!謝謝 – Nilesh

相關問題