Skip to content Skip to sidebar Skip to footer

Android: Accessing A Variable Of An Inner Asynctask Class But Getting It As Null In Oncreateview Of A Fragment

I have the following codes which get the value of LDR sensor from the cloud. The variable which I am trying to access is ldrVal but when I am trying to access that value outside th

Solution 1:

I think the value is showing correctly. I do not understand what do you want exactly. However, the values stored in lrdVal is fetched in the doInBackground method of your AsyncTask and then its initialized inside the AsyncTask. So the Toast is showing the non-zero value while inside your onCreateView function you are not getting the value, as the value is not set yet.

You need to check the Fragment lifecycle here, which clearly shows that the onCreateView is called before onActivityCreated. You are calling the new UbidotsConnection().execute(); method inside onActivityCreated which is initializing the value based on the code segment you have shared. So I think the behaviour is correct based on your implementation.

I'm not sure if either of them is possible though. I have to access ldrVal in onCreateView in order to perform some operations on it based if it exceeds a certain value.

You cannot get the updated value of ldrVal inside your onCreateView. Take the actions necessary inside your doInBackgroud method or inside the onPostExecute function of your AsyncTask where your updated value will be available for ldrVal.

I fetched ldrVal in onPostExecute but I still got it as 0 when I displayed variable in a Toast in onCreateView. Here is what I did: @Override protected void onPostExecute(Object o) { ldrVal= (int) ldrValues[0].getValue(); }

Instead of passing a generic Object o, you might consider passing the array instead, in your onPostExecute function.

publicclassUbidotsConnectionextendsAsyncTask<Void, Void, Value[]> {
    privatefinalStringAPI_KEY="XXXXXXXXXXXXXXXXX";
    privatefinalStringUBIDOTS_ID_FOR_LIGHT1="XXXXXXXXXXXXX";

    @Overrideprotected Value[] doInBackground(Void... params) {
        ApiClientapiClient=newApiClient(API_KEY);
        light = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT1);
        Value[] ldrValues = light.getValues();

        ldrVal = (int) ldrValues[0].getValue();
        //Toast.makeText(getActivity().getApplicationContext(), "ldr value: "+ldrVal,Toast.LENGTH_LONG).show();//toast giving correct value
        getActivity().runOnUiThread(newRunnable() {
            publicvoidrun() {
                Toast.makeText(getActivity().getApplicationContext(), "ldr value: " + ldrVal, Toast.LENGTH_SHORT).show();
            }
        });

        return ldrValues;
    }

    @OverrideprotectedvoidonPostExecute(Value[] values) {
        ldrVal = (int) values[0].getValue();
    }
}

Post a Comment for "Android: Accessing A Variable Of An Inner Asynctask Class But Getting It As Null In Oncreateview Of A Fragment"