Carl Bruiners
Carl Bruiners

Reputation: 87

Device rotation maintaining state

I'm aware that when you rotate a device, the view and activities are destroyed, so a new instance of both activity and fragment are created.

I pass into a fragment a matchid, which I'm presuming is also destoryed.

Code below, this is ran in a fragment (I have tried this in the onCreateView and also in the onViewCreated methods);

String getArgument = getArguments().getString("matchid");
    DatabaseReference database = FirebaseDatabase.getInstance().getReference();
    DatabaseReference ref = database.child("Matches");
    Query gameQuery = ref.orderByChild("gameID").equalTo(getArgument);
    gameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                TextView homeTeamSetTxt = (TextView) getView().findViewById(R.id.txtRefHomeTeam);

My question is how do you maintain state whilst rotating a device?

I don't want to lock the user to either orientation.

Upvotes: 0

Views: 29

Answers (1)

user456
user456

Reputation: 262

You can override

 @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("matchid", matchid);
    }

and when the screen is recreated

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dataGotFromServer = savedInstanceState.getString("matchid");
    }

Or you can use viewmodels which survives device rotations.

Hope that helpes

Upvotes: 2

Related Questions