我在onResume()
中有一个方法,它获取用户的数据,应该在用户启动应用程序时调用。这很好用。
问题是,例如,在打开"设置"后,当我点击/单击返回箭头时,onResume()
中的方法再次被调用,用户数据再次开始获取。
我想要的是,我希望只有当用户启动应用程序时才调用该方法,而不是每次用户从设置转换回主活动时。
这是MainActivity.java
:中的onResume()
@Override
protected void onResume() {
super.onResume();
fetchUserData();
}
以下是我如何过渡到Settings.java
:
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
请告诉我如何限制fetchUserData()
仅在用户启动应用程序时被调用,而不是在用户通过点击/单击后退箭头从任何其他活动转换回主活动时再次被调用。
抱歉,若问题的格式不正确。我在这里还是个初学者。
如果希望在活动打开时只调用一次方法,请将其移动到OnCreate()
方法中。CCD_ 8可以被调用多次。您可以在此处查看活动生命周期的文档
您可以调整以下代码,方法是设置一个标志/指示符,以便只处理所需的返回(例如,将resume_state设置为RESUMESTATE_NOTHING,除非在启动一个意图之后要获取UserData:-
public class AisleListByCursorActivity extends AppCompatActivity {
public final static int RESUMESTATE_NOTHING = 0;
public final static int RESUMESTATE_AISLEADD = 1;
public final static int RESUMESTATE_AISLESTOCK = 2;
public final static int RESUMESTATE_AISLEDELETE =3;
public final static int RESUMESTATE_AISLEUPDATE = 4;
public int resume_state = RESUMESTATE_NOTHING;
public ShopsCursorAdapter currentsca;
public AislesCursorAdapter currentaca;
public ShopListSpinnerAdapter currentslspa;
public long currentshopid;
private final static String THIS_ACTIVITY = "AisleListByCursorActivity";
private final ShopperDBHelper shopperdb = new ShopperDBHelper(this,null, null, 1);
private ListView aisleslistview;
private Cursor csr;
private int shopid = 0;
protected void onResume() {
super.onResume();
switch (resume_state) {
case RESUMESTATE_AISLEADD:case RESUMESTATE_AISLEUPDATE: {
Cursor csr = shopperdb.getAislesPerShopAsCursor(currentshopid);
currentaca.swapCursor(csr);
resume_state = RESUMESTATE_NOTHING;
break;
}
default: {
resume_state = RESUMESTATE_NOTHING;
}
}
}
public void aalbcadd(View view) {
resume_state = RESUMESTATE_AISLEADD;
Intent intent = new Intent(this,AisleAddActivity.class);
intent.putExtra("Caller",THIS_ACTIVITY);
intent.putExtra("SHOPID", currentshopid);
startActivity(intent);
}
在OnStart()
或onCreate()
而不是onResume()
中创建方法。参考-请参阅此链接以更好地了解Android生命周期http://developer.android.com/reference/android/app/Activity.html
如果希望只调用一次方法,则必须将该方法放入"活动"的onCreate
方法中。因为onResume
总是被调用,所以您会按照Android生命周期返回活动。因此,只需将方法fetchUserData();
替换为onCreate
,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
fetchUserData();
}
@Override
protected void onResume() {
super.onResume();
}