Reputation: 1557
I have two activities, Home.java
and Profile.java
.
When user clicks on someone's profile in ListView in Home.java I get username for that user, store it in static variable Home.usernameProfile
and go to Profile.java where I load data for clicked username using static variable Home.usernameProfile
.
From Profile you can go to another Profile (start new Profile.java
activity) and then you set Home.usernameProfile
for the new Profile.
Problem is that if I return from the second Profile to the first Profile in Home.usernameProfile
variable I will still have username for the second Profile, and I need to have username for the first Profile because I do things in Profile that requires Home.usernameProfile
variable.
I tried to create TextView in Profile.java, store Home.usernameProfile
variable value in a TextView and return it to Home.usernameProfile
on activity restart using public void onRestart() { super.onRestart(); ...}
, but TextView returns some other value.
Does anyone know how could I get username for currently displayed Profile when returning from other Profile?
Upvotes: 0
Views: 115
Reputation: 2324
You are using static variable at wrong place, don't do this. Static variable is class level variable and it is used to have single(common) value all the time for that class.
Read about static keyword here :- Official Doc
Changing static variable value will reflect variable's value at all places. (Think static as it will have only one value this value will be last assigned value. Changing value will overwrite its old value)
Problem :-
What is happening here when you start Profile.java and set value in Home.usernameProfile it works but again if you select other profile it will overwrite Home.usernameProfile value with new value. As this field is static in your scenario it will now have this new value at all places because you changed it intentionally. (This is how static works.)
For Solution :-
When coming from Home.java to Profile.java pass data using intent. Pass data from one activity to other. and remove static field from Home.java you don't need it now.
Now in Profile.java file you can easily get passed data and work with it.
Hope this helps,
Thanks.
Upvotes: 2