Forme
Forme

Reputation: 301

Calling a method from another Activity (call Fragment)

I have called method:

protected void ask(){

        Fragment newContent = new QuestionsFragment();
        ((MainActivity) getActivity()).switchContent(newContent, R.string.questions, MenuFragment.questions_id, BottomActionBarMode.QUESTIONS);
}

MainActivity: https://docs.google.com/file/d/0B30eXgoSJlFsczNSdkE5Qnc5eG8/edit?usp=sharing

Error:

08-21 17:16:28.574: E/AndroidRuntime(26360): FATAL EXCEPTION: main 08-21 17:16:28.574: E/AndroidRuntime(26360): java.lang.ClassCastException: com.chiv.successteritory.activities.AskLikeQuestionDetailsActivity cannot be cast to com.chiv.successteritory.activities.MainActivity

how to call? thanks in advance

Upvotes: 0

Views: 550

Answers (2)

Forme
Forme

Reputation: 301

In ask() AskLikeQuestionDetailsActivity:

Intent intent = new Intent(getActivity(), MainActivity.class);
        int condition = 1;
        intent.putExtra("condition", condition);
        startActivity(intent);

In onCreate() MainActivity.class:

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        showQuestions();
    }

Upvotes: 0

Hugo Hideki Yamashita
Hugo Hideki Yamashita

Reputation: 221

If you are on MainActivity and starts the AskLikeQuestionDetailsActivity, it's not guaranteed that MainActivity is still there, as the OS can garbage collect any Activities on background.

If you want change a Fragment on MainActivity after the ask() method is called on AskLikeQuestionDetailsActivity, I would suggest you to do the following:

On MainActivity, instead of calling startActivity to start AskLikeQuestionDetailsActivity, call startActivityForResult and override the onActivityResult method to change the Fragment depending on the result received.

On AskLikeQuestionDetailsActivity's ask(), call setResult with Activity.RESULT_OK and a configured Intent to send some information back to MainActivity, then call finish() (if you have to exit the AskLikeQuestionDetailsActivity Activity right away).

Is it clear? Hope it helps.

Upvotes: 2

Related Questions