Статические поля в классах Действия, гарантировал, что пережил создать/уничтожить цикл?

1) Доберитесь, все элементы в документе (document.getElementsByTagName ('* '))
2) Делают соответствие регулярного выражения на атрибуте имени класса элемента для каждого элемента

16
задан Matthias 28 October 2009 в 11:17
поделиться

2 ответа

The first part of this answer is really old -- see below for the right way to do it

You can use the Application object to store application persistent objects. This Android FAQ talks about this problem as well.

Something like this:

public class MyApplication extends Application{
    private String thing = null;

    public String getThing(){
        return thing;
    }

    public void setThing( String thing ){
        this.thing = thing;
    }
}

public class MyActivity extends Activity {
    private MyApplication app;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        app = ((MyApplication)getApplication());

        String thing = app.getThing();
    }
}

The right way:

When this answer was first written, the documentation for the Activity lifecycle was not as good as it is now. Reading Saving Activity State section on the Activity document helps us understand how Android wants us to save state. Essentially, there are two circumstances under which your activity starts: (1) as a new activity and (2) because of a configuration change or when it's recreated after being destroyed due to memory pressure. When your activity starts because it's a new activity, then saveInstanceState is null. It's not null otherwise. If it's null, then your activity should initialize itself from scratch. Fragments are very similar to Activities, and I covered this concept in detail for my AnDevCon-14 slide deck. You can also take a look at the sample code for my AnDevCon-14 presentation for more details.

Reworking my previous example would look something like the code below. I do change the semantics a bit -- in this second version I assume the string thing is specific to the activity within a specific android task, in the previous example it's ambiguous. If you do want to keep the same data around for multiple android tasks, then using either the Application object or another singleton is still your best bet.

public class MyActivity extends Activity {
    private static final String THING = "THING";

    private String thing;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState==null) {
            // First time here (since we last backed out at least)
            thing = initializeThing(); // somehow we init it
        } else {
            // Rehydrate this new instance of the Activity
            thing = savedInstanceState.getString(THING);
        }

        String thing = app.getThing();
    }

    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(THING, thing);
    }
}
15
ответ дан 30 November 2019 в 22:49
поделиться

Другой, тоже злой, способ сохранить статические данные - это заставить вас активировать одноэлементный класс. Этот синглтон будет хранить статическую ссылку на себя.

class EvilSingleton{
    private static EvilSingleton instance;

    //put your data as non static variables here

    public static EvilSingleton getInstance()
    {
        if(instance == null)
            instance = new EvilSingleton();
        return instance;
    }
}

В методе onCreate () вашей операции вы можете получить доступ / построить синглтон и любые данные, которые могут вам понадобиться. Таким образом, ваше действие или приложение могут быть уничтожены или воссозданы любое количество раз, и пока сохраняется пространство памяти вашего процесса, с вами должно быть все в порядке.

Это злой подрывной хак, так что нет обещания; -)

0
ответ дан 30 November 2019 в 22:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: