So I want to pass the data between the activities,so I've make that there's 3 separate integers should be send to the second activity,but i don't know why,the emulator keeps adding all of them. Basically,I making an app, at case of my course - i need to create an app that keeping score,in my case,app would keep the score,number of fouls,and number of corners during the football match. To set the data,we are clicking in special button (press score to increment score etc.) when we want to go to the second activity and see the detailed statistics we should see like 3 goals,6 fouls,and like 2 corners for team "A" during the match,but when i clicking in buttons (suppose that is 1 time for goal,2 times for fouls,and 3 times for corner the app should be like 1 goal,2 fouls,3 corner's but it keep adding all of integers,and it's like 6 goals,6 fouls,6 corners. What can be wrong?
Count activity (here program storage the value of integers)
public class CountActivity extends AppCompatActivity {
public int team_a_score;
public int team_a_foul;
public int team_a_corner;
public int team_b_score;
public int team_b_foul;
public int team_b_corner;
private Button goToDetailedStats;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count);
goToDetailedStats = (Button) findViewById(R.id.go_to_stats);
goToDetailedStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDetailedScore();
}
});
}
private void openDetailedScore() {
Intent intent = new Intent(this,DeatiledScoreActivity.class);
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
startActivity(intent);
}
public void resetScore(View view) {
team_a_score = 0;
display_a_score(team_a_score);
team_b_score = 0;
display_b_score(team_b_score);
}
private void display_a_score (int a_score){
TextView team_a_score_tv = (TextView) findViewById(R.id.team_a_score_tv);
team_a_score_tv.setText(String.valueOf(a_score));
}
private void display_b_score (int b_score){
TextView team_b_score_tv = (TextView) findViewById(R.id.team_b_score_tv);
team_b_score_tv.setText(String.valueOf(b_score));
}
public void increment_a_score(View view) {
team_a_score = team_a_score+1;
display_a_score(team_a_score);
}
public void increment_a_foul(View view) {
team_a_foul = team_a_foul+1;
}
public void increment_a_corner(View view) {
team_a_corner = team_a_corner+1;
}
public void increment_b_score(View view) {
team_b_score = team_b_score+1;
display_b_score(team_b_score);
}
public void increment_b_foul(View view) {
team_b_foul = team_b_foul+1;
}
public void increment_b_corner(View view) {
team_b_corner = team_b_corner+1;
}
}
Detailed activity have to receive data that we send as intent from Counting activity.
public class DeatiledScoreActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deatiled_score);
int team_a_score_detail_int = 0;
int team_a_foul_detail_int = 0;
int team_a_corner_detail_int = 0;
int team_b_score_detail_int = 0;
int team_b_foul_detail_int = 0;
int team_b_corner_detail_int = 0;
Intent goal_intent = getIntent();
int goal = goal_intent.getIntExtra("", team_a_score_detail_int);
display_a_goal(goal);
Intent foul_intent = getIntent();
int foul = foul_intent.getIntExtra("", team_a_foul_detail_int);
display_a_foul(foul);
Intent corner_intent = getIntent();
int corner = corner_intent.getIntExtra("", team_a_corner_detail_int);
display_a_corner(corner);
}
public void display_a_goal(int score) {
TextView a_score = (TextView) findViewById(R.id.team_a_goal_detail);
a_score.setText(String.valueOf(score));
}
public void display_a_foul(int foul){
TextView a_foul = (TextView) findViewById(R.id.team_a_foul_detail);
a_foul.setText(String.valueOf(foul));
They cannot have the same key:
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
So in order to make it work set:
intent.putExtra("some",team_a_score);
intent.putExtra("some2",team_a_foul);
intent.putExtra("some4",team_a_corner);
Intent putExtra method accepts two arguments key - value.
Related
So, I have an activity in my app where I need to take in the number of tickets for different ticket classes that are retrieved from the backend. The number of ticket classes is also variable. How do I take the user input in this case? Each time the countdown_btn or countup_btn is pressed, I need to update an array that holds the number of tickets the user has chosen. How do I do this when the number of ticket classes itself is dynamic?
If the button 'pledge' is clicked, I want to take the respective inputs from each of the views here and somehow communicate it to the next activity using intent.
My app's code:
public class RewardsAndPledgeActivity extends AppCompatActivity {
DatabaseReference mRewardsRef;
RecyclerView rewards_list;
String Artcall_id;
String reward_id[];
Integer counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_rewards);
/* -------- Obtain the Event ID of the item that the user has selected on the RecyclerView ------*/
Intent intent = getIntent();
Artcall_id = intent.getStringExtra("Artcall_id");
/* ----------------------------------------------------------------------------------------------*/
mRewardsRef = FirebaseDatabase.getInstance().getReference().child("Rewards").child(Artcall_id);
rewards_list = (RecyclerView) findViewById(R.id.reward_list);
rewards_list.setHasFixedSize(true);
rewards_list.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Reward_List, RewardsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Reward_List, RewardsViewHolder>(
Reward_List.class,
R.layout.single_reward_item_layout,
RewardsAndPledgeActivity.RewardsViewHolder.class,
mRewardsRef
) {
#Override
protected void populateViewHolder(final RewardsViewHolder viewHolder, Reward_List model, int position) {
final String reward_id = getRef(position).getKey();
viewHolder.setReward_ticket_amount_txt(model.getReward_ticket_amount_txt());
viewHolder.setReward_ticket_amount_class_name(model.getReward_ticket_amount_class_name());
viewHolder.setReward_ticket_class_desc(model.getReward_ticket_class_desc());
viewHolder.countdown_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer current_ticket_count = Integer.parseInt(viewHolder.ticket_counter.getText().toString());
if(current_ticket_count >0 ) {
viewHolder.ticket_counter.setText(String.valueOf(current_ticket_count - 1));
}
}
});
viewHolder.countup_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer current_ticket_count = Integer.parseInt(viewHolder.ticket_counter.getText().toString());
viewHolder.ticket_counter.setText(String.valueOf(current_ticket_count + 1));
}
});
}
};
rewards_list.setAdapter(firebaseRecyclerAdapter);
}
}
My database:
Image of the activity:
Below are the 3 java classes that I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array but I am quite confused on how the logic must be for the code to send the datas keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. Do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java - https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java - https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java - https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
you can store them as public static variable or create AddActivity constructor and get functions.
String student name; /*add value to this variable #onCreate or wherever in your AddActivity*/
public class AddActivity(/*here to pass data to addactivity*/){
//
}
public String getName(){
return this.name;
}
in another activity
AddActivity ac = new AddActivity();
String someName = ac.getName();
you can use this logic to pass data.
Edit
but if you want to pass data with Intent then just check intenr content onCreate()
Intent i = getIntent();
if(i.hasExtra("intentKey")){//check if it s not null
String name = i.getExtraString("intentKay");
}
The best solution I could find is, declare that array list as static and you could access those wherever you want provided if the classes are in the same package. But if you want to store those values, used shared preferences. Hope this may helps out.
I am beginner and I made a simple app to draw champions from the crystals (based on Marvel COC game theme :-)). I has two activity classes i.e. DrawActivity Class, has 3 buttons to Draw 1 or 5 or 10 Hero Crystals based on Random nos generated in Champ Activity. In the logcat i can see I/Choreographer﹕ Skipped 105 frames! The application may be doing too much work on its main thread. I read other posts, but cannot understand anything what I need to do to resolve it. Appreciate your help here.
Edit - I click the buttons and click back to come to drawActivity. Repeat it multiple times, thats when i get this intermittently.
public class DrawActivity extends Activity {
private TextView mChampsList;
private Button mDraw01Button;
private Button mDraw05Button;
private Button mDraw10Button;
private int noOfChamps;
public static final String TAG ="DrawChamps";
public static final String KEY_NUMOFCHAMPS ="DrawChamps_NoOfChamps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
mChampsList = (TextView) findViewById(R.id.champs_list);
// Log.d(TAG, ChampsActivity.getChampList());
mChampsList.setText(ChampsActivity.getChampList());
mDraw01Button = (Button) findViewById(R.id.draw1_button);
mDraw05Button = (Button) findViewById(R.id.draw5_button);
mDraw10Button = (Button) findViewById(R.id.draw10_button);
mDraw01Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noOfChamps = 1;
startChampActivity();
}
});
mDraw05Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noOfChamps = 5;
startChampActivity();
}
});
mDraw10Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noOfChamps = 10;
startChampActivity();
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_NUMOFCHAMPS, noOfChamps);
}
public void startChampActivity(){
Intent intent = new Intent(DrawActivity.this,ChampsActivity.class);
intent.putExtra(ChampsActivity.EXTRA_NUMOFCHAMPS,noOfChamps);
startActivity(intent);
}
Champ Activity - Draws the champs based on random no. and display it
public class ChampsActivity extends Activity {
private final static double fourStarHero = 0.04;
private final static double threeStarHero = 0.2;
private static int[] champCount = {0, 0, 0};
private static int noOfDraws=0;
private TextView mShowResult;
private static final String[] champsList = {"Thor", "Gamora", "Iron Fist", "Iron Man",
"Star Lord", "Dr. Strange", "Drax", "Juggernaut", "Storm", "Wolverine", "Hulk",
"Magneto", "Ultron", "Daredevil", "Capt. America", "Rocket Racoon","Magic","Black Panther"};
public static final String EXTRA_NUMOFCHAMPS = "ChampsAct_NoOfChamps";
public static final String TAG ="ChampsAct";
private static StringBuilder drawResultSet = new StringBuilder();
public static String getChampList() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < champsList.length; i++) {
result.append(champsList[i].toUpperCase()).append(", ");
}
return result.toString();
}
private static String getChampName() {
int rand = (int) (Math.random() * champsList.length);
return champsList[rand].toUpperCase();
}
private static void getChamps(int noOfChamps) {
drawResultSet.setLength(0);
for (int i = 0; i < noOfChamps; i++) {
double rand = Math.random();
if (rand < fourStarHero) {
champCount[2]++;
drawResultSet.append("4 Star ").append(ChampsActivity.getChampName()).append("\n");
} else if (rand < threeStarHero) {
champCount[1]++;
drawResultSet.append("3 Star ").append(ChampsActivity.getChampName()).append("\n");
} else {
champCount[0]++;
drawResultSet.append("2 Star ").append(ChampsActivity.getChampName()).append("\n");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_champs);
noOfDraws = getIntent().getIntExtra(EXTRA_NUMOFCHAMPS,1);
getChamps(noOfDraws);
//Log.d(TAG, drawResultSet.toString());
mShowResult = (TextView) findViewById(R.id.result_heroes);
mShowResult.setText(drawResultSet.toString());
}
}
I keep getting repeated issues with: variable is accessed from within inner class
every time i want to use an object etc from an onclicklistener etc.
I know the problem is that its not set to final, but if i set to final im not able to do anything to it before pressing the onclicklistener button...
Example i have an EditText field, which is filled with getText from an object, then i want to press an apply button and the object with the new text from the textfield.
This doesnt work when the object need to be final for the "inner class" to use it.
How do i best handle this? i keep running into this bloody phenonemon...
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
final ArrayList<PictureItem> tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tempArray.add(pi);
}
});
}
}
you should define tempArray variable outside of onCreate method.
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
ArrayList<PictureItem> tempArray
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tempArray.add(pi);
}
});
}
}
The problem is that you add th picture to a temporary array which is not accesible when you click on it. I think that you can do something like this to define the array outside the inCreate function.
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
final ArrayList<PictureItem> tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(PictureTalkFragment.array != null){
PictureTalkFragment.array.add(pi);
}
}
});
}
}
I'm doing an activity to measure how long it takes a person to do an exercise, but it has a bug that I couldn't resolve yet...
The TrainingFragment shows a list of exercises that the user can click and then my ExerciseActivity is launched and runs until the variable "remainingsSets" is setted to 0.
When I click in the first time at any exercise, everything works fine, the ExerciseActivity works correctly end return to the TrainingFragment. But then, if I try to click in another exercise, the ExerciseActivity is just closed.
In my debug, I could see that the variable "remainingSets" comes with it's right value (remainingSets = getIntent().getIntExtra("remaining_sets", 3)), but when the startButton is clicked, I don't know why the variable "remainingSets" is setted to 0 and then the activity is closed because this condition: if (remainingSets > 0){...}.
Here is my TrainingFragment:
public class TrainingFragment extends Fragment {
private final static int START_EXERCISE = 1;
private Training training;
private String lastItemClicked;
private String[] values;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Bundle bundle = getArguments();
if (bundle != null) {
training = bundle.getParcelable("training");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return (ScrollView) inflater.inflate(R.layout.template_exercises, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayout exercisesContainer = (LinearLayout) getView().findViewById(R.id.exercises);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
List<Exercise> exercises = training.getExercises();
values = new String[exercises.size()];
if (savedInstanceState != null) {
values = savedInstanceState.getStringArray("values");
}
for (int i = 0; i < exercises.size(); i++) {
final View exerciseView = inflater.inflate(R.layout.template_exercise, null);
exerciseView.setTag(String.valueOf(i));
TextView remainingSets = (TextView) exerciseView.findViewById(R.id.remaining_sets);
if (savedInstanceState != null) {
remainingSets.setText(values[i]);
} else {
String sets = exercises.get(i).getSets();
remainingSets.setText(sets);
values[i] = sets;
}
exerciseView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ExerciseActivity.class);
intent.putExtra("remaining_sets",
Integer.valueOf(((TextView) v.findViewById(R.id.remaining_sets)).getText().toString()));
lastItemClicked = v.getTag().toString();
startActivityForResult(intent, START_EXERCISE);
}
});
exercisesContainer.addView(exerciseView);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArray("values", values);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
View view = ((LinearLayout) getView().findViewById(R.id.exercises)).findViewWithTag(lastItemClicked);
if (requestCode == START_EXERCISE) {
if (resultCode == Activity.RESULT_OK) { // the exercise had been
// finished.
((TextView) view.findViewById(R.id.remaining_sets)).setText("0");
view.setClickable(false);
values[Integer.valueOf(lastItemClicked)] = "0";
} else if (resultCode == Activity.RESULT_CANCELED) {
String remainingSets = data.getStringExtra("remaining_sets");
((TextView) view.findViewById(R.id.remaining_sets)).setText(remainingSets);
values[Integer.valueOf(lastItemClicked)] = remainingSets;
}
}
}
}
My ExerciseActivity:
public class ExerciseActivity extends Activity {
private Chronometer chronometer;
private TextView timer;
private Button startButton;
private Button endButton;
private int remainingSets;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise);
ExerciseEvents.addExerciseListener(new PopupExerciseListener());
chronometer = (Chronometer) findViewById(R.id.exercise_doing_timer);
timer = (TextView) findViewById(R.id.timer);
startButton = (Button) findViewById(R.id.start_exercise);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ExerciseEvents.onExerciseBegin();
}
});
endButton = (Button) findViewById(R.id.end_exercise);
endButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ExerciseEvents.onExerciseRest();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("remaining_sets", String.valueOf(remainingSets));
setResult(RESULT_CANCELED, intent);
super.onBackPressed();
}
public class PopupExerciseListener implements ExerciseListener {
public PopupExerciseListener() {
remainingSets = getIntent().getIntExtra("remaining_sets", 3);
}
#Override
public void onExerciseBegin() {
if (remainingSets > 0) {
chronometer.setVisibility(View.VISIBLE);
timer.setVisibility(View.GONE);
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
startButton.setVisibility(View.GONE);
endButton.setVisibility(View.VISIBLE);
} else {
ExerciseEvents.onExerciseFinish();
}
}
#Override
public void onExerciseFinish() {
setResult(RESULT_OK);
finish();
}
#Override
public void onExerciseRest() {
chronometer.setVisibility(View.GONE);
endButton.setVisibility(View.GONE);
timer.setVisibility(View.VISIBLE);
long restTime = getIntent().getLongExtra("time_to_rest", 60) * 1000;
new CountDownTimer(restTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
ExerciseEvents.onExerciseBegin();
}
}.start();
remainingSets--;
}
}
}
And my ExerciseEvents:
public class ExerciseEvents {
private static LinkedList<ExerciseListener> mExerciseListeners = new LinkedList<ExerciseListener>();
public static void addExerciseListener(ExerciseListener listener) {
mExerciseListeners.add(listener);
}
public static void removeExerciseListener(String listener) {
mExerciseListeners.remove(listener);
}
public static void onExerciseBegin() {
for (ExerciseListener l : mExerciseListeners) {
l.onExerciseBegin();
}
}
public static void onExerciseRest() {
for (ExerciseListener l : mExerciseListeners) {
l.onExerciseRest();
}
}
public static void onExerciseFinish() {
for (ExerciseListener l : mExerciseListeners) {
l.onExerciseFinish();
}
}
public static interface ExerciseListener {
public void onExerciseBegin();
public void onExerciseRest();
public void onExerciseFinish();
}
}
Could anyone give me any help?
After you updated your code, I see you have a big memory leak in your code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise);
ExerciseEvents.addExerciseListener(new PopupExerciseListener());
....
}
The call ExerciseEvents.addExerciseListener(new PopupExerciseListener()) adds a new PopupExerciseListener to a static/global list: ExcerciseEvents.mExerciseListeners. Since the class PopupExerciseListener is an inner-class, it implicitly holds a reference to its enclosing ExcerciseActivity. This mean your code is holding on to each instance of ExcerciseActivity forever. Not good.
This may also explain the weird behavior you see. When one of the onExcersizeXXX() methods is called, it will call all ExcerciseListeners in the linked-list, the ones from previous screens and the current one.
Try this in your ExcerciseActivity.java:
....
ExerciseListener mExerciseListener;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
....
....
mExerciseListener = new PopupExerciseListener()
ExerciseEvents.addExerciseListener(mExerciseListener);
....
....
}
#Override
protected void onDestroy() {
ExerciseEvents.removeExerciseListener(mExerciseListener);
super.onDestroy();
}
....
In onDestroy, you deregister your listener, preventing a memory leak and preventing odd multiple callbacks to PopupExerciseListeners that are attached to activities that no longer exist.