2017-03-27 92 views
0

我有我的VehicleListActivity它通過Bundle我的片段。 這是活動的onCreate方法:片段的onCreateView調用之前的活動的onCreate

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_vehicle_list); 
    vehicles = new ArrayList<>(); 

    Intent intent = getIntent(); 
    String userID = intent.getStringExtra("userID"); 
    LoadingVehicleListFragment f = new LoadingVehicleListFragment(); 
    Bundle fArguments = new Bundle(); 
    fArguments.putString("userID", userID); 
    f.setArguments(fArguments); 
    getSupportFragmentManager().beginTransaction().add(R.id.loadingVehicleFragment, f).commit(); 
} 

,這是片段的onCreateView

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    activity = (VehicleListActivity)getActivity(); 
    context = activity; 
    listener = activity; 
    String userID = getArguments().getString("userID"); 
    getUserInformation(userID); 

    return inflater.inflate(com.devspark.progressfragment.R.layout.fragment_progress, container, false); 
} 

我注意到片段的onCreateView之前活動的onCreate被調用,所以在我的片段返回空值,這導致空指針異常。 我應該在哪裏放置以避免此異常?

編輯:根據要求,這是整個片段的來源:

public class LoadingVehicleListFragment extends ProgressFragment 
{ 
private VehicleListListener listener; 
private VehicleListActivity activity; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    return inflater.inflate(com.devspark.progressfragment.R.layout.fragment_progress, container, false); 
} 

/*@Override 
public void onActivityCreated(@Nullable Bundle savedInstanceState) 
{ 
    super.onActivityCreated(savedInstanceState); 
    int c = 0; 
    listener = (VehicleListActivity)getActivity(); 
    getUserInformation(getArguments().getString("userID")); 
}*/ 

private void getUserVehicles(String userID) 
{ 
    Response.Listener<String> responseListener = new Response.Listener<String>() 
    { 
     @Override 
     public void onResponse(String response) 
     { 
      try 
      { 
       HashMap resultMap = new ObjectMapper().readValue(response, HashMap.class); 
       VehicleListRequest.ErrorCode errorCode = VehicleListRequest.ErrorCode.fromInt(Integer.parseInt(resultMap.get("error_code").toString())); 

       switch (errorCode) 
       { 
        case NONE: 
         parseVehicleFromMap(resultMap); 
         break; 
        case EXCEPTION_CAUGHT: 
         AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity()); 
         builder2.setMessage("Eccezione catturata. \n Messaggio: " + resultMap.get("error_message")); 
         builder2.create().show(); 
         break; 
       } 
      } 
      catch (IOException e) 
      { 
       // TODO gestire 
       e.printStackTrace(); 
      } 
     } 
    }; 

    VehicleListRequest request = new VehicleListRequest(userID, responseListener, null); 
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); 
    requestQueue.add(request); 
} 

public void getUserInformation(final String userID) 
{ 
    Response.Listener<String> responseListener = new Response.Listener<String>() 
    { 
     @Override 
     public void onResponse(String response) 
     { 
      try 
      { 
       HashMap resultMap = new ObjectMapper().readValue(response, HashMap.class); 
       GetUserRequest.ErrorCode errorCode = GetUserRequest.ErrorCode.fromInt(Integer.parseInt(resultMap.get("error_code").toString())); 

       switch (errorCode) 
       { 
        case NONE: 
         listener.setLoggedUser(User.fromMap(resultMap)); 
         getUserVehicles(userID); 
         break; 
        case EXCEPTION_CAUGHT: 
         AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity()); 
         builder2.setMessage("Eccezione catturata. \n Messaggio: " + resultMap.get("error_message")); 
         builder2.create().show(); 
         break; 
       } 
      } 
      catch (IOException e) 
      { 
       // TODO gestire 
       e.printStackTrace(); 
      } 
     } 
    }; 

    GetUserRequest request = new GetUserRequest(userID, responseListener, null); 
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); 
    requestQueue.add(request); 
} 

private void parseVehicleFromMap(HashMap map) 
{ 
    int i = 0; 

    while (map.containsKey(String.valueOf(i))) 
    { 
     final Vehicle v = new Vehicle(); 
     HashMap vehicleMap = (HashMap) map.get(String.valueOf(i)); 

     v.setPlate(vehicleMap.get("plate").toString()); 
     v.setKm(vehicleMap.get("km") == null ? null : Integer.parseInt(vehicleMap.get("km").toString())); 
     v.setInUse(Integer.parseInt(vehicleMap.get("in_use").toString()) == 1); 
     v.setFuelQuantity(Double.parseDouble(vehicleMap.get("actual_fuel_quantity").toString())); 
     v.setEffectiveFuelEconomy(Double.parseDouble(vehicleMap.get("effective_fuel_economy").toString())); 
     v.setInsuranceDate(vehicleMap.get("insurance_date") == null ? null : new LocalDate(vehicleMap.get("insurance_date").toString())); 
     v.setMatriculationDate(new LocalDate(vehicleMap.get("matriculation_date").toString())); 
     v.setLatitude(vehicleMap.get("latitude") == null ? null : Double.parseDouble(vehicleMap.get("latitude").toString())); 
     v.setLongitude(vehicleMap.get("longitude") == null ? null : Double.parseDouble(vehicleMap.get("longitude").toString())); 
     v.setUser(activity.getLogged()); 

     listener.addVehicle(v); 

     i++; 
    } 
} 
} // end class 

這是錯誤日誌:

03-27 18:30:47.274 4966-4966/clyky.cartracker E/AndroidRuntime: FATAL EXCEPTION: main 
                  Process: clyky.cartracker, PID: 4966 
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{clyky.cartracker/clyky.cartracker.activities.VehicleListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference 
                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434) 
                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504) 
                   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347) 
                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                   at android.os.Looper.loop(Looper.java:148) 
                   at android.app.ActivityThread.main(ActivityThread.java:5458) 
                   at java.lang.reflect.Method.invoke(Native Method) 
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference 
                   at clyky.cartracker.activities.fragments.LoadingVehicleListFragment.onActivityCreated(LoadingVehicleListFragment.java:51) 
                   at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2193) 
                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1323) 
                   at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1523) 
                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1585) 
                   at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2832) 
                   at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201) 
                   at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:603) 
                   at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:181) 
                   at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237) 
                   at android.app.Activity.performStart(Activity.java:6268) 
                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2397) 
                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)  
                   at android.app.ActivityThread.-wrap11(ActivityThread.java)  
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)  
                   at android.os.Handler.dispatchMessage(Handler.java:102)  
                   at android.os.Looper.loop(Looper.java:148)  
                   at android.app.ActivityThread.main(ActivityThread.java:5458)  
                   at java.lang.reflect.Method.invoke(Native Method)  
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  

這些異常之前,我也得到了一些「失敗粘合劑交易」一樣,這些:

03-27 18:30:41.955 1452-1452/com.google.android.inputmethod.latin E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 100) 

03-27 18:30:41.956 1452年至1452年/ com.google.android.inputmethod.latin E/Androi dimE:aqx:java.lang.RuntimeException:android.os.DeadObjectException:小宗地上的交易失敗;遠程進程可能已經死亡 03-27 18:30:41.999 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 100) 03-27 18:30:42.000 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:事務處理失敗包;遠程進程可能已經死亡 03-27 18:30:42.001 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 100) 03-27 18:30:42.002 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:事務處理失敗包;遠程進程可能已經死亡 03-27 18:30:42.005 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 100) 03-27 18:30:42.007 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:事務處理失敗包;遠程進程可能已經死亡 03-27 18:30:42.008 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 100) 03-27 18:30:42.010 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:事務處理失敗包;遠程進程可能已經死亡 03-27 18:30:42.026 1452-5094/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 168) 03-27 18:30:42.031 1452-5095/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 168) 03-27 18:30:43.509 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (宗地大小= 100) 03-27 18:30:43.510 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:事務處理失敗包;遠程進程可能已經死亡 03-27 18:30:43.510 1452-1452/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 100) 03-27 18:30:43.512 1452-1452/com.google.android.inputmethod.latin E/AndroidIME:aqx:java.lang.RuntimeException:android.os。DeadObjectException:小宗地上的交易失敗;遠程進程可能已經死亡 03-27 18:30:43.542 1452-5121/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (parcel size = 168) 03-27 18:30:43.547 1452-5120/com.google.android.inputmethod.latin E/JavaBinder:!!!失敗的粘合劑交易!!! (包裹大小= 168)

但是,它們開始出現在拋出異常的操作之前,所以我認爲這些錯誤沒有影響。

+0

你爲什麼要在onCreateview中調用super.onAttach?你也可以在'onCraateView'中使用'getArguments()',這個缺點是執行速度較慢onCreateView – Bhargav

+0

@Bhargav抱歉'onAttach',這是一個複製粘貼錯誤'因爲我試圖在片段的onAttach中執行'getArguments'第一個 – Clyky

+0

等待是甚至爲片段膨脹的觀點? – Remario

回答

1

當創建主機活動時,在onCreateView()方法之後調用onActivityCreated()。已創建活動和片段實例以及活動的視圖層次結構。此時,可以使用findViewById()方法訪問視圖。例。在這個方法中,你可以實例化需要一個Context對象的對象。

嘗試訪問它的存在,也不要存放在片段背景下隨時撥打getActivity()

那空指針被執行的Android框架的流動引起的,onCreateView()系統調用該回調時,它的時間片段第一次繪製其用戶界面。要爲您的片段繪製UI,您必須從此方法返回一個View組件,該方法是片段佈局的根。如果片段不提供UI,則可以返回null。因此它被首先調用,因此給出空指針異常。

+0

嘗試獲取該方法中的參數。 – Remario

+0

謝謝你的回答。正如你所說,我試圖在'onActivityCreated'中獲取參數,但它仍然不起作用。現在活動的'onCreated'被調用,但是'onActivityCreated'永遠不會被調用(我放在那裏的斷點永遠不會被調用) – Clyky

+0

這是有線的,我會建議使用共享的首選項文件來共享感興趣的內容。 – Remario

0

你可以試試嗎?

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_vehicle_list); 
    vehicles = new ArrayList<>(); 

    String userID; 
    Bunlde bundle = getIntent().getExtras(); 
    if(bundle != null){ 
     userID = bundle.getString("userID"); 
    } 

    if(savedInstanceState == null){ 
      LoadingVehicleListFragment f = new LoadingVehicleListFragment(); 
      Bundle fArguments = new Bundle(); 
      fArguments.putString("userID", userID); 
      f.setArguments(fArguments); 
      getSupportFragmentManager().beginTransaction().replace(R.id.loadingVehicleFragment, f).commit(); 
    } 
} 
+0

謝謝,我試過了,但'onActivityCreated'中的'getArguments'仍然返回null – Clyky

+0

您可以發送整個片段代碼嗎?這裏有些不對勁。 – savepopulation

+0

是的,我已經編輯了我的最初發帖 – Clyky

相關問題