Warning:(40, 5) Do not place Android context classes in Static Fields; this is a memory Leak (and also breaks Instant Run)

Asked

Viewed 261 times

2

I’m coming across this warning from Android Studio. Warning:(40, 5) Do not place Android context classes in Static Fields; this is a memory Leak (and also breaks Instant Run) I have a button that opens a Datepicker Fragment to select the date.

// Botão para chamar o DatePicker Fragment na Activity principal
    btnSelecionaData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

When selecting the date I pass this information to an Edittext that is in the class that called this Datepicker Fragment with a . setText() but for this to work Edittext needs to be Static and why Android Studio keeps giving this warning.

// Classe DatePickerFragment
public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user

        //######### ESTE É O EDITTEXT STATIC DA ACTIVITY PRINCIPAL, O QUAL EU PRECISO SETAR COM A DATA ASSIM QUE O USUÁRIO CLICAR NO OK DO FRAGMENT
        etAniver.setText(day+"/"+(month+1)+"/"+year);
        //#########
    }
}

I still don’t understand 100% how language works, so I ask... You have a problem leaving it the way it is?

It seems to me that there is no problem, the value of the variable is needed only while the user is in Activity because once he clicks save the data will be saved in the database and the value of the variable will no longer matter. As I understand this String will be in memory, then it will be replaced by the new value when the user registers another customer. So the memory occupied by 1 static variable would be insignificant... would that be it? Or the data that goes through this variable overlap in memory?

  • The DatePickerFragment is being used for something? Why not use directly the DatePickerDialog?

  • How and where you declare etAniver?

  • Victor, etAniver is outside the Oncreate in the main Activity, which calls the Datepicker.

  • Leonardo, I don’t know, I searched a lot until I found this functional hahahaha

  • This class returns a Datepickerdialog, but has how to create this Datepickerdialog within the main Activity?

  • Victor, etAniver is declared this way: public static EditText etAniver;

  • Victor, the link between the variable and Edittext is made inside Oncreate in this way: etAniver = (EditText) findViewById(R.id.et_aniver);

  • Leonardo, I tried using the direct Datepickerdialog but my project is for API 19 and to use the Ondatesetlistener I need API 24 above

  • @Pablohenriquecorrea Do not put the solution to the problem in the answer. [en.so] is a question and answer system, so the answer should be in the answer area. There is no problem answering the question itself, so use the "Post your answer" button at the bottom of the page. It is also unnecessary to add "Solved" in the heading Just mark an answer as accepted you are already indicating that the problem has been solved.

  • Thanks Anderson, this is my first post.

  • To solve this problem, just follow that answer here.

Show 6 more comments

2 answers

5

You have a problem leaving it the way it is?

Yes you have.

This will/may cause the memory used by the application to grow progressively.

This happens because part of the memory allocated in this process will not be released when it is no longer needed(memory Leak/memory leak).

The problem is that Edittext, as well as any other type of View, has a reference to a Context, probably in this case an Activity.

An Activity, in the course of using the application, can be destroyed and recreated by the system.
In order that no more than one Activity exists in memory, the memory allocated by the destroyed Activity must be able to be released.

Edittext, when declared static, will exist throughout the entire existence of the application. By keeping the reference to Activity, used to create it, it will not allow the memory allocated to it to be released, if another one has been created.

That is, the problem is not the amount of memory that occupies Edittext but the instances that are referenced by it that cannot be released when they are no longer accurate.

  • Thank you your Ramaral, was extremely enlightening.

  • Look at this reply where it explains how to communicate between Fragment and Activity .

  • Very good your Ramaral, I managed to understand a little more the logic, but I still could not solve because the Onattach was deprecated and the new way to create the Datepickerdialog new OnDateSetListener() as it is for API 24 above and bad design is for API 19 above

  • Although obsolete can use the onAttach(Activity activity. In relation to OnDateSetListener() I don’t understand what you mean.

  • beauty I’ll try it like this with regards to Ondatesetlistener: It has a very easy way to create a Datepickerdialog with an Ondatesetlistener but only from API 24, my project is API 19, the code I believe would look like this: DatePickerDialog datePicker = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
 @Override
 public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
 
 }
 })

  • Now I understand. That would avoid having to implement what is said in that answer. If you fix the principle it’s almost the same.

  • In relation to the method onAttach(Activity activity) use the onAttach(Context context).

  • Dear, I found a simpler solution than I imagined, I’m going to post

  • Note that the question refers to Warning and if "Is it a problem to leave it as it is?". So it is not up to the answer to give an alternative to the code posted.

  • I believe so your Ramaral, because as you answered my question... "Is it OK to leave it as it is?" You answered that you have a problem, so we have a problem and the modified code section solves exactly this problem (memory Leak/memory leak)

  • If another person with the same problem that I read this post would already know to solve, now without the passage changed, the doubts for other people who access remains

Show 6 more comments

1


I was able to solve the problem (memory Leak/memory leak) just by editing the Ondateset method inside the Datepickerfragment class. It was like this:

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
    TextView tv1= (TextView) getActivity().findViewById(R.id.et_aniver);
    tv1.setText(view.getDayOfMonth()+"/"+(view.getMonth()+1)+"/"+view.getYear());

}

This way the Edittext variable in the main Activity nay needs to be Static, thus solving the problem of (memory Leak/memory leakage). The statement was so now:

private EditText etAniver;
  • Gee, I can’t understand you guys, why can’t you write it down if the problem’s solved? This makes everything clearer to readers, makes reading easier. And why the hell can’t I thank you?? It was just a thank you to the people who helped me. Are you anti-social??? Or did I miss some rule?

  • We are by no means anti-social. Everything has to be how stackoverflow works. I suggest that I law it tour and the topics of Help center. If you were looking for an answer to solve the Warning should have done so. However, the way you did it will help many more users, since this Warning may arise in many other situations and not only in your (type of) code.

  • Relax, I’m deleting my account, I see no basis in other people being able to change my posts, it’s like putting words in my mouth.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.