应用正确的活动生命周期方法

时间:2013-03-25 19:46:16

标签: java android

更新

这是我的listview应用程序:

enter image description here

我点击启动意图的电子邮件选项并加载我的电子邮件活动:

enter image description here

如果用户点击“返回”,则列表视图为空白:

enter image description here

这是我设置列表视图的方法:

    public class view extends ListActivity {

ImageButton searchButton;
EditText searchName;
ListView searchedListResults;
long idToPass;
String numReturned;
String email;
SimpleCursorAdapter cursorAdapter;
DBHandler getCons;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    searchedListResults = (ListView) findViewById(android.R.id.list);

    list();

    searchName = (EditText) findViewById(R.id.inputName);

    searchedListResults.setTextFilterEnabled(true);

    searchName.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            cursorAdapter.getFilter().filter(s.toString());

            searchedListResults.refreshDrawableState();

        }

    });

    getCons = new DBHandler(this, null, null);

    cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {

            getCons.open();
            return getCons.getChanges(constraint.toString());

        }

    });
    searchedListResults.setAdapter(cursorAdapter);
}

private void list() {
    DBHandler DBsearchRef = new DBHandler(this, null, null);

    DBHandler search = new DBHandler(this, null, null);

    search.open();
    Cursor cursor = search.getData();
    search.close();
    startManagingCursor(cursor);

    String[] from = new String[] { DBsearchRef.KEY_NAME,
            DBsearchRef.KEY_TEL, DBsearchRef.KEY_EMAIL,
            DBsearchRef.KEY_COMMENTS };
    int[] to = new int[] { R.id.txtNameSet, R.id.txtContactSet,
            R.id.txtEmailSet, R.id.txtCommentSet };

    cursorAdapter = new SimpleCursorAdapter(this, R.layout.searchagain,
            cursor, from, to);
    searchedListResults.setAdapter(cursorAdapter);

}

@Override
protected void onResume() {
    super.onResume();

    list();

    searchName = (EditText) findViewById(R.id.inputName);

    searchedListResults.setTextFilterEnabled(true);

    searchName.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            cursorAdapter.getFilter().filter(s.toString());

            searchedListResults.refreshDrawableState();

        }

    });

    getCons = new DBHandler(this, null, null);

    cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {

            getCons.open();
            return getCons.getChanges(constraint.toString());

        }

    });
    searchedListResults.setAdapter(cursorAdapter);
}

@Override
public void onListItemClick(ListView list, View v, int list_posistion,
        long item_id) {
    idToPass = item_id;

    idToPass = item_id;

    DBHandler num = new DBHandler(this, null, null);

    num.open();
    numReturned = num.getNum(idToPass);

    email = num.getEmail(idToPass);
    num.close();

    final CharSequence[] items = { "Call Contact", "Email Contact",
            "Edit Contact", "Add Appointment" };

    Builder alertDialogBuilder = new AlertDialog.Builder(view.this);

    alertDialogBuilder.setTitle("Contact Options:");

    alertDialogBuilder.setItems(items,
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {

                    if (items[item].equals("Call Contact")) {

                        Intent makeCall = new Intent(Intent.ACTION_DIAL,
                                Uri.parse("tel:" + numReturned));
                        startActivity(makeCall);
                    }

                    else if (items[item].equals("Email Contact")) {

                        Intent emailIntent = new Intent(
                                "com.example.flybaseapp.ContactsEmail");
                        emailIntent.putExtra("passedEmailAdd", email);
                        startActivity(emailIntent);
                    } else if (items[item].equals("Edit Contact")) {

                        Intent Edit = new Intent(
                                "com.example.flybaseapp.viewEdit");
                        Edit.putExtra("passedID", idToPass);
                        startActivity(Edit);

                    }

                    else if (items[item].equals("Add Appointment")) {

                        Intent conAdd = new Intent(
                                "com.example.flybaseapp.AddAppointmentContact");
                        conAdd.putExtra("newpassedID", idToPass);
                        startActivity(conAdd);

                    }
                }

            });

    alertDialogBuilder.show();

}

是否在重写onResume方法中设置它?

3 个答案:

答案 0 :(得分:0)

可以在此处找到Android活动生命周期:

http://developer.android.com/reference/android/app/Activity.html

enter image description here

答案 1 :(得分:0)

活动 lifecycle 已经在实施您的活动的所有阶段。除了你需要自己定义的onCreate()之外。

如果您需要在这些阶段执行某些特定操作,请在此生命周期中调用其他阶段

我们以LoginActivity为例。


您可以像这样创建活动(我知道......这里没什么新内容):

public class LoginActivity extends Activity {

    public EditText usr;
    public EditText pass;
    final Context context = this;
    private TextView loginButton;
    private Boolean justCreated = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initLoginButton();

        initEditTexts();

        addSwipeGesture();

        justCreated = true;
    }

现在让我们假设登录已成功验证,并且活动将进入下一步的简短而紧张的生命周期。这将是 onPause()阶段。这意味着活动将在“背景”中。

用户设置为用户名和密码的字符串会发生什么?..好吧,如果你不将它们保存在某处,那么如果用户导航回登录屏幕,它们就会丢失(这意味着活动是重新创建)。

在这种情况下,你需要@Override onPause()方法并对这些字符串做一些事情。为简单起见,我将使用一个名为SavedValues的已创建公共类,我将保存这些字符串。


SavedValues类:

public class SavedValues {

    private static String loginUser = "";
    private static String loginPassword = "";


    public static String getLoginUser() {
        return loginUser;
    }

    public static void setLoginUser(String loginUser) {
        SavedValues.loginUser = loginUser;
    }

    public static String getLoginPassword() {
        return loginPassword;
    }

    public static void setLoginPassword(String loginPassword) {
        SavedValues.loginPassword = loginPassword;
    }
}


现在......活动中包含的onPause()方法:

public class LoginActivity extends Activity {

    public EditText usr;
    public EditText pass;
    final Context context = this;
    private TextView loginButton;
    private Boolean justCreated = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initLoginButton();

        initEditTexts();

        addSwipeGesture();

        justCreated = true;
    }

@Override
public void onPause() {
    super.onPause();

    SavedValues.setLoginUser(usr.getText().toString());
    SavedValues.setLoginPassword(pass.getText().toString());

    justCreated = false;
}   

到目前为止,一切都很好,很花哨。现在,当用户导航回LoginActivity时,它将进入其生命周期的onResume()阶段。如果我们什么也不做,那么我们保存的值就不会被设置。

因此,我们将覆盖onResume()方法,以便在LoginActivity从睡眠中醒来时检索这些值:

public class LoginActivity extends Activity {

    public EditText usr;
    public EditText pass;
    final Context context = this;
    private TextView loginButton;
    private Boolean justCreated = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        initLoginButton();

        initEditTexts();

        addSwipeGesture();

        justCreated = true;
    }

@Override
public void onPause() {
    super.onPause();

    SavedValues.setLoginUser(usr.getText().toString());
    SavedValues.setLoginPassword(pass.getText().toString());

    justCreated = false;
}

@Override
public void onResume() {
    super.onResume();

    if (justCreated == true) //if the user recreated the activity, restore the login values from the previous instance
    {
        usr.setText(SavedValues.getLoginUser(), TextView.BufferType.EDITABLE);
        pass.setText(SavedValues.getLoginPassword(), TextView.BufferType.EDITABLE);

        usr.setSelection(usr.getText().length());
    }
    else //if the user only left the activity clear the login values
    {
        usr.setText("", TextView.BufferType.EDITABLE);
        pass.setText("", TextView.BufferType.EDITABLE);
    }
}



因此,您可以使用Activity的生命周期中的某些阶段来获得优势。当然,还有更多,但我认为这应该让你开始。请在Android Dev. Site上阅读更多信息。他们有一个不错的文档,虽然是非线性的混乱方式。


更新

要回答您更新的问题:

您可以使用我的SavedValues示例,并将其放入:

private static ArrayList<Custom> yourList;

public static ArrayList<Custom> getyourList() {
        return yourList;
}

public static void setyourList(ArrayList<Custom> yourList) {
        SavedValues.yourList = yourList;
}

然后在你的onPause()方法中写下这个:

@Override
public void onPause() {

    SavedValues.setyourList(getyourList()); // save the selected item list
    super.onPause();
    }

现在,如果您按下后退按钮并返回到您的活动,则数据应该在那里。

通过使用从Oracle DB填充的Array适配器,我使用了几乎相同的方法。像魅力一样。



干杯,祝你好运!

答案 2 :(得分:0)

Android Lifecycle将在时间运行时运行必要的方法,即使它们没有写入代码中。 onCreate()是您override唯一需要的state。所有其他人都将根据您Activity所在的override运行。但是,如果需要,您可以onResume()使用这些方法中的任何一种或全部。

例如,每次Activity变为可见时都会运行onCreate(),但Actviity仅在首次创建onResume()时运行,您可以选择放置代码在Activity中确保每次Activity变为可见时都会运行它。或者您可能希望在@Override public void finish() { super.finish(); // save variable to sharedprefs or wherever here } 被销毁时保存变量

{{1}}