Serkay Sarıman
Serkay Sarıman

Reputation: 475

Call fragment method from activity but view is null

I am checking internet connection in my main activity.If connection is lost,I want to show reconnecting message in fragment.Example:If I run following code in main activity my app is crashing.

ConversationFragment conv1 = new ConversationFragment();
conv1.showReconnecting();

And this is the showReconnecting method in fragment:

public void showReconnecting() {
    final RelativeLayout rel=(RelativeLayout)rootView.findViewById(R.id.reconnecting);
    rel.setVisibility(View.VISIBLE);
}

I know why my app is crashing because rootView is setting in onCreateView and when I call this method from activity rootView is returning null.

What can I do for resolve this problem ?

Upvotes: 2

Views: 469

Answers (3)

joao2fast4u
joao2fast4u

Reputation: 6892

According to what you want to do, a simple ProgressDialog will do the job. You can lauch it from your ChatFragment, like this:

First, declare it on your Fragment:

private ProgressDialog connectiongProgressDialog;

Then, when you want to show it, use:

connectiongProgressDialog = ProgressDialog.show(getActivity(), "My title", "Reconnecting");

When you want to dismiss it, use:

if (connectiongProgressDialog != null){
    connectiongProgressDialog .dismiss();
}

It will display a simple dialog with the message you want.

Upvotes: 0

Chirag Jain
Chirag Jain

Reputation: 1612

Try this (Assuming reconnecting view is in fragment and your fragment is visible on screen),

public void showReconnecting() {
    if (conv1 != null && conv1.getView()!=null) {
        final RelativeLayout rel=(RelativeLayout)conv1.getView().findViewById(R.id.reconnecting);
        rel.setVisibility(View.VISIBLE);
    }
}

If conv1 is not available then please make it class variable.

Upvotes: 1

AmaJayJB
AmaJayJB

Reputation: 1453

Well, just looking at this and your explanation, I would think you can't call methods relating to a view (such as a fragment) without creating said fragment. An option, if the fragment is only used for showing the reconnecting, would be just to put some code in the activity and use a Toast.makeText(....).show(); which notifies the user that you are attempting to reconnect. So instead of conv1.showReconnecting(); maybe rather put, Toast.makeText(context,"Reconnecting", Toast.LONG).show(); and then do the necessary background work in an AsyncTask.

I hope this helps.

Upvotes: 0

Related Questions