在活动onCreate

时间:2017-03-27 15:19:06

标签: android android-fragments android-activity

我的VehicleListActivityBundle传递给我的片段。 这是活动的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之前被调用,因此片段中的getArguments()返回null,这会导致空指针异常。 我应该将getArguments()放在我的片段中以避免此异常?

编辑:根据要求,这是整个片段的来源:

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 / AndroidIME:aqx:java.lang.RuntimeException:android.os.DeadObjectException:小包裹上的交易失败;远程过程可能已经死亡 03-27 18:30:41.999 1452-1452 / com.google.android.inputmethod.latin E / JavaBinder:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 168) 03-27 18:30:42.031 1452-5095 / com.google.android.inputmethod.latin E / JavaBinder:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 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:!!!失败的粘合剂交易! (包裹大小= 168) 03-27 18:30:43.547 1452-5120 / com.google.android.inputmethod.latin E / JavaBinder:!!!失败的粘合剂交易! (包裹大小= 168)

然而,它们开始出现在抛出异常的操作之前,所以我认为这些错误没有影响。

2 个答案:

答案 0 :(得分:1)

创建主机活动时,在onActivityCreated()方法之后调用onCreateView()。已创建活动和片段实例以及活动的视图层次结构。此时,可以使用findViewById()方法访问视图。例。在此方法中,您可以实例化需要Context对象的对象。

尝试在那里访问它,也不要在片段中存储上下文,总是调用getActivity()

Null Pointer是由android框架中的执行流引起的,onCreateView()系统在片段第一次绘制其用户界面时调用此回调。要为片段绘制UI,必须从此方法返回View组件,该组件是片段布局的根。如果片段不提供UI,则可以返回null。 因此首先调用它,因此给出空指针异常。

答案 1 :(得分:0)

你能试试吗?

class ThirdWindow(QWidget, Ui_Form3):
    def __init__(self):
        super(ThirdWindow, self).__init__()
        self.dbu = DatabaseHandling.DatabaseUtility()
        self.msl = None

        # Show UI on screen + resize window
        self.setupUi(self)
        self.picIndicator.setPixmap(QPixmap("M:\QtProjects\\Resources\\138691.png"))
        self.setFixedSize(350, 480)

        #  Define what should happen on button click
        self.btnQuit.clicked.connect(self.close)
        self.btnSixtyPercent.clicked.connect(self.check_clicked)
        self.btnTenPercent.clicked.connect(self.check_clicked)
        self.btnFivePercent.clicked.connect(self.check_clicked)


    #  TODO: Create a window that ask's for the spot it's specific color
    '''def indication(self):
        d = DialogOne()
        d.exec_()'''

    def check_clicked(self):
        print("{}%".format(self.sender().text()))