0

In fragment'A' when a certain condition is established, it should go to 'ChatActivity'.

Intent intent = new Intent(getContext(), ChatActivity.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("uid", matchedUid);
startActivity(intent);

The problem is when other fragment or Activity is showing on the top, the condition is established so startActivity is not executed.. occur an error

'java.lang.String android.content.Context.getPackageName()' on a null object reference

below is entire code

public class MatchFragment extends Fragment implements MatchMVP.View {

private static final String TAG = "MatchFragment";

private MatchPresenter matchPresenter;

private ToggleButton randomMatchBtn;
private ProgressBar progressBar, progressCircle;
private TextView searchingText;

private AdView adView;

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View v;

    setupMVP();

    if(matchPresenter.checkOnlineStatus(getContext())) {
        v = inflater.inflate(R.layout.fragment_match, container, false);
        setupView(v);
        matchPresenter.isSearching();
        initAd(v);
    } else {
        v = inflater.inflate(R.layout.fragment_offline, container, false);
    }

    return v;
}

private void setupMVP() {
    matchPresenter = new MatchPresenter(this);
}

private void setupView(View v) {

    progressBar = v.findViewById(R.id.progressbar);
    progressCircle = v.findViewById(R.id.progressbar_circle);
    searchingText = v.findViewById(R.id.searching_text);

    progressBar.setVisibility(View.INVISIBLE);
    progressCircle.setVisibility(View.INVISIBLE);
    searchingText.setVisibility(View.INVISIBLE);

    randomMatchBtn = v.findViewById(R.id.random_match_btn);
    randomMatchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(matchPresenter.checkOnlineStatus(getContext())) {
                if(randomMatchBtn.isChecked()) {
                    matchPresenter.searchRandomUser();
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    matchPresenter.stopMatch();
                    progressBar.setVisibility(View.VISIBLE);
                }
            } else {
                showSnackBar("error");
            }
        }
    });
}

private void initAd(View v) {
    MobileAds.initialize(getActivity(), "ca-app-pub-6263138384822549~5566878684");

    adView = v.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
}

@Override
public void createChatRoom(String matchedUid) {
    Intent intent = new Intent(getContext(), ChatActivity.class);
    intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("uid", matchedUid);
    startActivity(intent);

    Vibrator vibrator;
    if(getContext() != null) {
        vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(700);
    }
}

@Override
public void showSnackBar(String msg) {
    Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content), msg, 2500);
    View snackBarLayout = snackbar.getView();
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
    );
    // Layout must match parent layout type
    lp.setMargins(0, 300, 0, 0);
    // Margins relative to the parent view.
    snackBarLayout.setLayoutParams(lp);
    snackbar.show();
}

@Override
public void randomMatchBtnOff() {
    randomMatchBtn.setChecked(false);
}

@Override
public void randomMatchBtnDisable() {
    randomMatchBtn.setEnabled(false);
}

@Override
public void randomMatchBtnEnable() {
    randomMatchBtn.setEnabled(true);
    progressBar.setVisibility(View.INVISIBLE);
}

@Override
public void showProgressCircle() {
    progressCircle.setVisibility(View.VISIBLE);
    searchingText.setVisibility(View.VISIBLE);
}

@Override
public void hideProgressCircle() {
    progressCircle.setVisibility(View.INVISIBLE);
    searchingText.setVisibility(View.INVISIBLE);
}

@Override
public void goAuthActivity() {
    Intent intent = new Intent(getContext(), AuthActivity.class);
    intent.putExtra("isSanctioned", true);
    startActivity(intent);
    assert getActivity() != null;
    getActivity().finish();
}

@Override
public void onResume() {
    super.onResume();
    matchPresenter.checkIsSan();
}

@Override
public void onPause() {
    super.onPause();

    if(isThreadRunning) {
        timeCheckThread.interrupt();
    }
}

}

Cause of error is 'Fragment is not attached to its Activity'. Yeah I know. I'm making a randomChatting app with firebase. In this MatchFragment, I'm searching other users. When other users start searching, matched with me then let me know by go to 'ChatActivity'.

But if I'm in other fragment of activity, searching is activating, it can't go ChatActivity. 'Fragment is not attached to its Activity'.

Because I'm in other activity not in this MatchFragment. MatchFragment detached to its Activity.

How go to ChatActivity even if I'm in other activity.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
J.Dragon
  • 699
  • 8
  • 16
  • 1
    Share the code where you are using getPackageName() – Yash Aug 15 '19 at 17:59
  • It sounds like this code isn't even being executed when "the condition" is established. It sounds like you need to find a better place to run this code. – jeff Aug 15 '19 at 18:01
  • @YashKrishanVerma I'm not using getPackageName(). The error part is 'Intent intent = new Intent(getActivity(), ChatActivity.class);' – J.Dragon Aug 15 '19 at 18:26
  • 1
    `getActivity()` is returning null, which would indicate that the `Fragment` is not attached to its `Activity` when that code runs. You've not provided enough information for us to be able to determine exactly why. Please look into how to put together a [mcve]. – Mike M. Aug 15 '19 at 18:33
  • share the complete fragment class – Yash Aug 15 '19 at 18:38
  • 1
    Please edit your question to provide more context - there isn't enough information here to debug the problem. Add the complete stacktrace to your question, provide the code that corresponds to said stacktrace (is it this section that launches a new activity?), and show us where you call the code causing this crash. – PPartisan Aug 15 '19 at 18:39
  • @PPartisan Sorry guys. I have edited. – J.Dragon Aug 15 '19 at 18:53
  • `Because I'm in other activity not in this MatchFragment. MatchFragment dettached to its Activity.` - So why is this logic inside `MatchFragment`? If the Fragment is detached then why is it responsible for launching your chat activity? I actually wonder *how* it's even being called, as I assume your `Presenter` calls this method, and when the Fragment is detached then the Presenter shouldn't exist? – PPartisan Aug 15 '19 at 19:03
  • @PPartisan Finally I decided 'startActivity' logic put in a Service. Thank you – J.Dragon Aug 16 '19 at 10:02

1 Answers1

0

You can either try using requireActivity() instead of getActivity() but since you only need a Context object and not necessarily an Activity object, I suggest you replace getActivity() with requireContext().

If that doesn't work out then you can try following this answer: https://stackoverflow.com/a/30498143

PS: I know this should be shared as a comment but my reputation is currently only 41 and I can't post a comment so writing this as an answer.

VarunBarad
  • 376
  • 3
  • 8
  • Thanks for your answer. But it is not working. Even solution of attached link is not working too. onAttach(Activity activity) is deprecated. – J.Dragon Aug 15 '19 at 18:15
  • You can try to use `onAttach(Context context)` as that is not deprecated. – VarunBarad Aug 15 '19 at 19:09