PubNub映射错误

时间:2018-03-13 06:36:09

标签: android pubnub

我有一个活动" HomeActivity"其中有一个片段,其中一个是#34; PeopleMEFragment"。 当我点击" People"选项卡/文本,我每次启动应用程序时都会得到以下错误,然后随机:

 Attempt to invoke virtual method 'com.google.gson.JsonObject com.google.gson.JsonElement.getAsJsonObject()' on a null object reference
                                                                               at com.pubnub.api.managers.MapperManager.elementToInt(MapperManager.java:94)
                                                                               at com.pubnub.api.endpoints.presence.HereNow.parseMultipleChannelResponse(HereNow.java:136)
                                                                               at com.pubnub.api.endpoints.presence.HereNow.createResponse(HereNow.java:105)
                                                                               at com.pubnub.api.endpoints.presence.HereNow.createResponse(HereNow.java:29)
                                                                               at com.pubnub.api.endpoints.Endpoint$1.onResponse(Endpoint.java:195)
                                                                               at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6153)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)

HomeActivity.java

public class HomeActivity extends ParentActivity implements View.OnClickListener, OnUserLocationUpdateListener {
private PubNub pubnub;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_home);
    overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
    window = getWindow();
    token = SharedPrefrencesHelper.getAuthToken(this);

    final PNConfiguration config = new PNConfiguration();
    user_id = SharedPrefrencesHelper.getUserId(context);
    config.setPublishKey(Constants.PUBNUB_PUBLISH_KEY);
    config.setSubscribeKey(Constants.PUBNUB_SUBSCRIBE_KEY);
    config.setUuid("ASK_" + SharedPrefrencesHelper.getUserEmail(context));
    config.setHeartbeatNotificationOptions(PNHeartbeatNotificationOptions.ALL);
    //  config.setPresenceTimeoutWithCustomInterval(5, 2);

    pubnub = new PubNub(config);
    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status) {
           /* subscribeToPresence(chanelList);
            changeAndSavePresence(SharedPrefrencesHelper.getPresence(HomeActivity.this));*/
        }

        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            Intent intent = new Intent("com.pubnub.update");
            intent.putExtra("channel_id", message.getChannel());
            intent.putExtra("DATA", String.valueOf(message.getMessage()));
            sendBroadcast(intent);
        }

        @Override
        public void presence(PubNub pubnub, PNPresenceEventResult presence) {
            if (presence != null) {
                String chanel = presence.getChannel();

                if (!chanel.equals("ASK_" + SharedPrefrencesHelper.getUserEmail(context))) {
                    if (presence.getState() != null) {

                        String status = presence.getState().toString();
                        try {
                            JSONObject jsonObject = new JSONObject(status);
                            status = jsonObject.optString("isstatus", "Offline");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        if (!globalArray.hereNowAskerChanelsforMentor.contains(chanel)) {
                            globalArray.hereNowAskerChanelsforMentor.add(chanel);
                            PresenceData data = new PresenceData();
                            data.email = chanel;
                            data.status = status;
                            globalArray.presenceArray.add(data);
                        } else {
                            int pos = globalArray.hereNowAskerChanelsforMentor.indexOf(chanel);
                            globalArray.presenceArray.get(pos).status = status;

                        }
                        Intent intent = new Intent("com.update.stataus");
                        intent.putExtra("CHANEL", chanel);
                        intent.putExtra("STATUS", status);
                        sendBroadcast(intent);
                        changeAndSavePresence(SharedPrefrencesHelper.getPresence(HomeActivity.this));
                    } else {
                        if (!globalArray.hereNowAskerChanelsforMentor.contains(chanel)) {
                            globalArray.hereNowAskerChanelsforMentor.add(chanel);
                            PresenceData data = new PresenceData();
                            data.email = chanel;
                            data.status = "Offline";
                            globalArray.presenceArray.add(data);
                        }
                    }

                }
            }

        }
    });
    pubnub.subscribe().channels(Arrays.asList("ASK_" + SharedPrefrencesHelper.getUserEmail(context))).withPresence().execute();
}
if (flag.equals("peopletab")) {

        title.setText(R.string.txt_people);
        title.setTextColor(Color.parseColor("#ffffff"));
        mCreditLinearLayout.setVisibility(View.GONE);

        imgQA.setImageResource(R.drawable.question_mark);
        imgMessage.setImageResource(R.drawable.message_icon);
        imgMyprofile.setImageResource(R.drawable.ask_iconn);
        imgPeople.setImageResource(R.drawable.people_hover);
        imgMore.setImageResource(R.drawable.my_profile_icon);

        mQaTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
        mMsgTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
        mAskQATabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
        mPeopleTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolorwithhover));
        mMyAccountTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));

       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(getResources().getColor(R.color.StatusbarRed));
        }*/
        final Drawable drawable6 = ContextCompat.getDrawable(context, R.drawable.header_gradient_color).mutate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mHeaderLayout.setBackground(drawable6);
        } else {
            mHeaderLayout.setBackgroundDrawable(drawable6);
        }

        imageAsk.setImageDrawable(getResources().getDrawable(R.drawable.askwhite));
        // menuIcon.setImageDrawable(getResources().getDrawable(R.drawable.search_button));
        txtAsk.setVisibility(View.GONE);
        imageAsk.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
        txtCounter.setVisibility(View.GONE);
        shareImage.setVisibility(View.GONE);
        txtAsk.setTextColor(Color.WHITE);
        settingIcon.setVisibility(View.GONE);
        title.setText("People");
        title.setTextColor(Color.parseColor("#ffffff"));
        menuIcon.setVisibility(View.GONE);
        mImageBack.setVisibility(View.GONE);

       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(getResources().getColor(R.color.StatusbarRed));
        }*/
        final Drawable drawable5 = ContextCompat.getDrawable(context, R.drawable.header_gradient_color).mutate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mHeaderLayout.setBackground(drawable5);
        } else {
            mHeaderLayout.setBackgroundDrawable(drawable5);
        }

        PeopleMEFragment peopleFragment = new PeopleMEFragment();
        FragmentManager peoplemanager = getSupportFragmentManager();
        FragmentTransaction peopletransaction = peoplemanager.beginTransaction();
        SharedPrefrencesHelper.saveTabValue(context, 1);
        peopletransaction.replace(R.id.content_frame, peopleFragment);
        peopletransaction.commit();

    } 
mScheduleTaskExecutor = Executors.newScheduledThreadPool(1);
    mScheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (chanelList.size() != 0) {
                        config.setHeartbeatNotificationOptions(PNHeartbeatNotificationOptions.ALL);
                        config.setPresenceTimeoutWithCustomInterval(5, 2);
                        //subscribeToPresence(chanelList);
                        changeAndSavePresence(SharedPrefrencesHelper.getPresence(HomeActivity.this));
                        getChannelStatus();
                    }
                }
            });

        }
    }, 0, 3, TimeUnit.SECONDS);
}
@Override
public void onClick(View view) {

    switch (view.getId()) { case R.id.peopleTabLayout:

            Fragment peoplefragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);

            if (!(peoplefragment instanceof PeopleMEFragment)) {
                clearBackStack();
                title.setText(getString(R.string.txt_people));
                mCreditLinearLayout.setVisibility(View.GONE);
                imgQA.setImageResource(R.drawable.question_mark);
                imgMessage.setImageResource(R.drawable.message_icon);
                imgMyprofile.setImageResource(R.drawable.ask_iconn);
                imgPeople.setImageResource(R.drawable.people_hover);
                imgMore.setImageResource(R.drawable.my_profile_icon);

                mQaTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
                mMsgTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
                mAskQATabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));
                mPeopleTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolorwithhover));
                mMyAccountTabTxt.setTextColor(getResources().getColor(R.color.bottambarcolor));

           /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.setStatusBarColor(getResources().getColor(R.color.StatusbarRed));
            }*/
                final Drawable drawable2 = ContextCompat.getDrawable(context, R.drawable.header_gradient_color).mutate();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mHeaderLayout.setBackground(drawable2);
                } else {
                    mHeaderLayout.setBackgroundDrawable(drawable2);
                }

                title.setTextColor(Color.parseColor("#ffffff"));
                menuIcon.setVisibility(View.GONE);
                mImageBack.setVisibility(View.GONE);
                imageAsk.setImageDrawable(getResources().getDrawable(R.drawable.askwhite));
                txtAsk.setVisibility(View.GONE);
                imageAsk.setVisibility(View.GONE);
                imageView.setVisibility(View.GONE);
                txtCounter.setVisibility(View.GONE);
                shareImage.setVisibility(View.GONE);
                txtAsk.setTextColor(Color.WHITE);
                settingIcon.setVisibility(View.GONE);

                PeopleMEFragment peopleFragment = new PeopleMEFragment();
                FragmentManager peoplemanager = getSupportFragmentManager();
                FragmentTransaction peopletransaction = peoplemanager.beginTransaction();
                SharedPrefrencesHelper.saveTabValue(context, 1);
                peopletransaction.replace(R.id.content_frame, peopleFragment);
                //peopletransaction.addToBackStack(null);
                peopletransaction.commit();
            }


            break;
}
}
private void getChannelStatus() {
    try {
        pubnub.hereNow().includeState(true).channels(chanelList).async(new PNCallback<PNHereNowResult>() {
            @Override
            public void onResponse(PNHereNowResult result, PNStatus status) {
                if (status.isError()) {
                    // handle error
                    return;
                }
                if (result != null) {
                    if (result.getChannels() != null) {
                        for (PNHereNowChannelData entry : result.getChannels().values()) {
                            for (PNHereNowOccupantData occupant : entry.getOccupants()) {
                                String chanel_id = occupant.getUuid();
                                String state = String.valueOf(occupant.getState());

                                if (!chanel_id.equals("ASK_" + SharedPrefrencesHelper.getUserEmail(context))) {

                                    String crappyPrefix = "null";

                                    if (state.startsWith(crappyPrefix)) {
                                        state = state.substring(crappyPrefix.length(), state.length());
                                    }

                                    if (!state.isEmpty()) {
                                        String user_status = "";

                                        try {
                                            JSONObject jsonObject = new JSONObject(state);

                                            if (jsonObject.has("isstatus")) {
                                                user_status = jsonObject.optString("isstatus", "Offline");
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        if (!user_status.isEmpty()) {
                                            if (!globalArray.hereNowAskerChanelsforMentor.contains(chanel_id)) {
                                                globalArray.hereNowAskerChanelsforMentor.add(chanel_id);
                                                PresenceData data = new PresenceData();
                                                data.email = chanel_id;
                                                data.status = user_status;
                                                globalArray.presenceArray.add(data);
                                            } else {
                                                int pos = globalArray.hereNowAskerChanelsforMentor.indexOf(chanel_id);
                                                globalArray.presenceArray.get(pos).status = user_status;

                                            }

                                            Log.d("Email", chanel_id);
                                            Log.d("Status Channel", user_status);
                                            Intent intent = new Intent("com.update.stataus");
                                            intent.putExtra("CHANEL", chanel_id);
                                            intent.putExtra("STATUS", user_status);
                                            sendBroadcast(intent);
                                            // changeAndSavePresence(SharedPrefrencesHelper.getPresence(HomeActivity.this));
                                        }


                                    }

                                } else if (!chanel_id.equals("MEN_" + SharedPrefrencesHelper.getUserEmail(context))) {

                                    String crappyPrefix = "null";

                                    if (state.startsWith(crappyPrefix)) {
                                        state = state.substring(crappyPrefix.length(), state.length());
                                    }

                                    if (!state.isEmpty()) {
                                        String user_status = "";
                                        try {
                                            JSONObject jsonObject = new JSONObject(state);
                                            if (jsonObject.has("isstatus")) {
                                                user_status = jsonObject.optString("isstatus", "Offline");
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        if (!user_status.isEmpty()) {
                                            if (!globalArray.hereNowAskerChanelsforMentor.contains(chanel_id)) {
                                                globalArray.hereNowAskerChanelsforMentor.add(chanel_id);
                                                PresenceData data = new PresenceData();
                                                data.email = chanel_id;
                                                data.status = user_status;
                                                globalArray.presenceArray.add(data);
                                            } else {
                                                int pos = globalArray.hereNowAskerChanelsforMentor.indexOf(chanel_id);
                                                globalArray.presenceArray.get(pos).status = user_status;

                                            }

                                            Log.d("Email", chanel_id);
                                            Log.d("Status Channel", user_status);
                                            Intent intent = new Intent("com.update.stataus");
                                            intent.putExtra("CHANEL", chanel_id);
                                            intent.putExtra("STATUS", user_status);
                                            sendBroadcast(intent);
                                            //       changeAndSavePresence(SharedPrefrencesHelper.getPresence(HomeActivity.this));

                                        }
                                    }
                                }


                            }
                        }
                    }
                }


            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

}

PeopleMEFragment.java

public class PeopleMEFragment extends Fragment implements PeopleAdapter.ChatClickCallback {

PubNub pubNub;


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    context = getActivity();
    final PNConfiguration config = new PNConfiguration();
    config.setPublishKey(Constants.PUBNUB_PUBLISH_KEY);
    config.setSubscribeKey(Constants.PUBNUB_SUBSCRIBE_KEY);
    config.setUuid("ASK_" + SharedPrefrencesHelper.getUserEmail(context));
    config.setHeartbeatNotificationOptions(PNHeartbeatNotificationOptions.ALL);

    pubNub = new PubNub(config);
}
@SuppressLint("StaticFieldLeak")
private class TaskGetPeopleSearch extends AsyncTask<Void, Void, Void>{

    String response = null;
    PeopleModel model;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {
            if (AppUtility.isNotNullEmpty(getActivity())) {
                progressBar.setVisibility(View.VISIBLE);
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } @Override
    protected Void doInBackground(Void... voids) {
        try {
            requesturl = Constants.PROTOCOL + Constants.HOST + Constants.PEOPLE_LIST_SEARCH_BY_ROLEID;JsonParser jsonParser = new JsonParser();
           response = jsonParser.makeServiceCall(requesturl, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void vVoid){
        super.onPostExecute(vVoid);
pubNub.getPresenceState().channels(Arrays.asList(channel + SharedPrefrencesHelper.getUserEmail(context)))
                                .uuid(channel+SharedPrefrencesHelper.getUserEmail(context)).async(new PNCallback<PNGetStateResult>() {
                            @Override
                            public void onResponse(PNGetStateResult result, PNStatus status) {
                          String state=      result.getStateByUUID().toString().replace("[","").replace("]","").replace("\"","");

                            }
                        });
}
}

HereNow.java

public class HereNow extends Endpoint<Envelope<JsonElement>, PNHereNowResult> {
private List<String> channels;
private List<String> channelGroups;
private Boolean includeState;
private Boolean includeUUIDs;

public HereNow(PubNub pubnubInstance, TelemetryManager telemetryManager, RetrofitManager retrofit) {
    super(pubnubInstance, telemetryManager, retrofit);
    channels = new ArrayList<>();
    channelGroups = new ArrayList<>();
}

@Override
protected List<String> getAffectedChannels() {
    return channels;
}

@Override
protected List<String> getAffectedChannelGroups() {
    return channelGroups;
}

@Override
protected void validateParams() throws PubNubException {
    if (this.getPubnub().getConfiguration().getSubscribeKey() == null || this.getPubnub().getConfiguration().getSubscribeKey().isEmpty()) {
        throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_SUBSCRIBE_KEY_MISSING).build();
    }
}

@Override
protected Call<Envelope<JsonElement>> doWork(Map<String, String> params) {
    if (includeState == null) {
        includeState = false;
    }
    if (includeUUIDs == null) {
        includeUUIDs = true;
    }
    String channelCSV;
    if (includeState) {
        params.put("state", "1");
    }
    if (!includeUUIDs) {
        params.put("disable_uuids", "1");
    }
    if (channelGroups.size() > 0) {
        params.put("channel-group", PubNubUtil.joinString(channelGroups, ","));
    }
    if (channels.size() > 0) {
        channelCSV = PubNubUtil.joinString(channels, ",");
    } else {
        channelCSV = ",";
    }
    if (channels.size() > 0 || channelGroups.size() > 0) {
        return this.getRetrofit().getPresenceService().hereNow(this.getPubnub().getConfiguration().getSubscribeKey(), channelCSV, params);
    } else {
        return this.getRetrofit().getPresenceService().globalHereNow(this.getPubnub().getConfiguration().getSubscribeKey(), params);
    }
}

@Override
protected PNHereNowResult createResponse(Response<Envelope<JsonElement>> input) {
    PNHereNowResult herenowData;
    if (channels.size() > 1 || channelGroups.size() > 0) {
        herenowData = parseMultipleChannelResponse(input.body().getPayload());
    } else {
        herenowData = parseSingleChannelResponse(input.body());
    }
    return herenowData;
}

private PNHereNowResult parseSingleChannelResponse(Envelope<JsonElement> input) {
    PNHereNowResult hereNowData = PNHereNowResult.builder().totalChannels(1).channels(new HashMap<String, PNHereNowChannelData>()).totalOccupancy(input.getOccupancy()).build();
    PNHereNowChannelData.PNHereNowChannelDataBuilder hereNowChannelData = PNHereNowChannelData.builder().channelName(channels.get(0)).occupancy(input.getOccupancy());
    if (includeUUIDs) {
        hereNowChannelData.occupants(prepareOccupantData(input.getUuids()));
        hereNowData.getChannels().put(channels.get(0), hereNowChannelData.build());
    }
    return hereNowData;
}

private PNHereNowResult parseMultipleChannelResponse(JsonElement input) {
    MapperManager mapper = getPubnub().getMapper();
    PNHereNowResult hereNowData = PNHereNowResult.builder().channels(new HashMap<String, PNHereNowChannelData>()).totalChannels(mapper.elementToInt(input, "total_channels")).totalOccupancy(mapper.elementToInt(input, "total_occupancy")).build();
    for (Iterator<Map.Entry<String, JsonElement>> it = mapper.getObjectIterator(input, "channels"); it.hasNext(); ) {
        Map.Entry<String, JsonElement> entry = it.next();
        PNHereNowChannelData.PNHereNowChannelDataBuilder hereNowChannelData = PNHereNowChannelData.builder().channelName(entry.getKey()).occupancy(mapper.elementToInt(entry.getValue(), "occupancy"));
        if (includeUUIDs) {
            hereNowChannelData.occupants(prepareOccupantData(mapper.getField(entry.getValue(), "uuids")));
        } else {
            hereNowChannelData.occupants(null);
        }
        hereNowData.getChannels().put(entry.getKey(), hereNowChannelData.build());
    }
    return hereNowData;
}

private List<PNHereNowOccupantData> prepareOccupantData(JsonElement input) {
    List<PNHereNowOccupantData> occupantsResults = new ArrayList<>();
    MapperManager mapper = getPubnub().getMapper();
    if (includeState != null && includeState) {
        for (Iterator<JsonElement> it = mapper.getArrayIterator(input); it.hasNext(); ) {
            JsonElement occupant = it.next();
            PNHereNowOccupantData.PNHereNowOccupantDataBuilder hereNowOccupantData = PNHereNowOccupantData.builder();
            hereNowOccupantData.uuid(mapper.elementToString(occupant, "uuid"));
            hereNowOccupantData.state(mapper.getField(occupant, "state"));
            occupantsResults.add(hereNowOccupantData.build());
        }
    } else {
        for (Iterator<JsonElement> it = mapper.getArrayIterator(input); it.hasNext(); ) {
            JsonElement occupant = it.next();
            PNHereNowOccupantData.PNHereNowOccupantDataBuilder hereNowOccupantData = PNHereNowOccupantData.builder();
            hereNowOccupantData.uuid(mapper.elementToString(occupant));
            hereNowOccupantData.state(null);
            occupantsResults.add(hereNowOccupantData.build());
        }
    }
    return occupantsResults;
} 

}

由于角色限制,课程没有完整的代码,所以我添加了所有细节,但我可能是崩溃的原因。 请帮助,因为我在最近几天坚持这一点。

1 个答案:

答案 0 :(得分:1)

您的片段对象可能为null。请在if语句中添加一个空检查,如下所示:

public void onClick(View view) {

    switch (view.getId()) { case R.id.peopleTabLayout:

        Fragment peoplefragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);

        if (peoplefragment != null && !(peoplefragment instanceof PeopleMEFragment)) {
                clearBackStack();

在尝试引用片段之前,请务必在检索片段的任何位置执行此操作。