我的活动启动了两次

时间:2017-01-15 19:25:52

标签: android android-studio android-activity firebase firebase-realtime-database

我有setOnItemClickListener()方法的listview,点击后我希望它打开新活动并给它2个额外项目,项目编号和登录用户(返回主屏幕),问题是活动开始两次,一次有好的额外活动,一次有" 0"在额外的位置...

此代码应检查Firebase服务器是否已放入其中(不超过5个玩家),如果是,则将用户添加到服务器并加入会议室(启动ServerActivity)。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            myRef = database.getReference("Servers/S"+position);
            myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    int i = 0;
                    while (dataSnapshot.child("player"+i).child("username").getValue() != null)
                        i++;
                    if (i < 5) {
                        Log.d("Implementing Child","player"+i);
                        CustomUser customUser = new CustomUser(false,currentUser.getUsername(),"",0,currentUser.getWins());
                        myRef.child("player" + i).setValue(customUser);

                    Intent intent = new Intent(GameActivity.this,ServerActivity.class);
                    intent.putExtra("serverNum",position);
                    intent.putExtra("currentUser",currentUser);
                    Log.d("position", position + "");
                    startActivity(intent);
                    finish();
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Server Full", Toast.LENGTH_SHORT).show();
                        myRef.child("isJoinable").setValue(false);
                    }
                    adapter.notifyDataSetChanged();


                }
                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Toast.makeText(getApplicationContext(), "" +
                            "Internet Error", Toast.LENGTH_SHORT).show();
                }
            });
            Intent intent = new Intent(GameActivity.this,ServerActivity.class);
            intent.putExtra("currentUser",currentUser);
            startActivity(intent);
            finish();
            //TODO FIX: activity probebly launches twice
        }
    });

我尝试在清单中修改LaunchMode但导致失败导致&#34; serverNum&#34;额外为0而不是位置。

1 个答案:

答案 0 :(得分:2)

为什么要添加此代码:

        Intent intent = new Intent(GameActivity.this,ServerActivity.class);
        intent.putExtra("currentUser",currentUser);
        startActivity(intent);
        finish();

这会在添加侦听器后立即启动ServerActivity。您是否尝试过评论此代码并仅使用onDataChange中的代码?