【问题标题】:Strange behavior when an activity is launched the second time第二次启动活动时的奇怪行为
【发布时间】:2013-06-13 11:07:16
【问题描述】:

我有一个Activity1,它启动Activity2Activity2 有一个列表,其中显示了数据库中的一些值。

Activity2 首次启动时,列表会显示正确的信息,但如果我按下返回按钮然后再次启动Activity2,它会从数据库中正确加载信息,但不会显示在列表中。

Activity1开始Activity2的代码:

final Intent int2 = new Intent(getActivity(), CombinationsManagerActivity.class);
MyActivity.insertSomeExtraInfoToTheIntent(int2, currentEmployee.id);
getActivity().startActivity(int2);

Activity2 列表代码是这样的(我在活动向服务器注册时调用它(在 onResume 之后)):

private void fillList() {

        list = (ListView) findViewById(R.id.list_combinations);
        ZKEmployeeLoginCombination combinations = ZKEmployeeLoginCombination.selectLoginCombinationsByEntityID(this, idEmployee);
        LoginCombinationsListAdapter adapter = new LoginCombinationsListAdapter(this, combinations, enrolledTypes);
        list.setAdapter(adapter);

    }

另外,Activity2 清单声明:

  <activity
            android:name="com.blabla.android.app.employeemanagementv3.CombinationsManagerActivity"
            android:label="@string/combinations_manager" >
        </activity>

任何帮助将不胜感激。

【问题讨论】:

  • 我真的不知道为什么会发生这种情况,但是如果你在第二个活动中按下后退按钮时调用完成()怎么办?你试过吗?
  • 你在哪里调用了这个方法 fillList() 。
  • 另一种可能是Activity2每次都在同一个任务中打开。建议在清单中添加 android:launchMode="singleTop"
  • 嗨@Opiatefuchs,谢谢你的回答,我试过了,但结果是一样的:通话结束并再次开始活动后,它不显示列表
  • @Sam 当我收到来自服务器的连接时,我在 onResume() 之后调用了 fillList()

标签: android android-listview android-activity


【解决方案1】:

最后我发现了我的代码中的错误:为了项目需求,我们保留了一些结构来充当服务器事件的侦听器。而registration 就是其中之一。

从活动中注册监听器的方法是:

private static IncomingEventHandler eventHandler = new IncomingEventHandler();
...
if(eventHandler.get(this.name) == null){
eventHandler.add(this.name, this);
}

所以我保留了上一个活动的引用,然后,当活动收到我们在帖子中执行的registration 事件时:

referenceToActivity.doSomeStuffOnUIThreadAfterRegister();

第一次运行良好,但在第二次执行中,referenceToActivity 指向第一个活动

【讨论】:

    【解决方案2】:

    您可能只希望应用程序中有一个活动 Activity2。如果是这样,我建议您在 Activity2 的清单中包含以下内容

    android:launchMode="singleTask"
    

    这可能会解决您的问题。有关说明,请参阅the android documentation

    【讨论】:

    • 谢谢,我试过了(也是singleTop),结果还是一样。
    • 在那种情况下我不确定。我建议您通过添加Log.d(...) 的负载进行调试以确定执行路径,还要确定第二个activity2 对象是否与第一次相同,查找创建和销毁的活动以检查是否一切正常,等等等等。祝你好运!
    【解决方案3】:

    只需将此代码 sn-p 放在您的 Activity2 类中尝试一下

        @Override
        public void onBackPressed() {
            Intent startNewActivityOpen = new Intent(Activity2.this, Activity1.class);
            startActivity(startNewActivityOpen);
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      相关资源
      最近更新 更多