Класс androidviewmodel возвращает значение null - PullRequest
0 голосов
/ 01 августа 2020
• 1000 line: selectedngame = game при создании ошибки должна получить выбранную игру, но вместо этого она по какой-то причине получает null
public class HomeViewModel extends AndroidViewModel {

private MutableLiveData<User> user = new MutableLiveData<>();
private MutableLiveData<Game> game = new MutableLiveData<>();
private SharedPreferences usernameSharedPreferences;
private SharedPreferences gameSharedPreferences;

public HomeViewModel(Application application) {
    super(application);
    usernameSharedPreferences = getApplication().getSharedPreferences("users",0);
    String username = usernameSharedPreferences.getString("username","");
    gameSharedPreferences = getApplication().getSharedPreferences("game",0);
    String gameName = gameSharedPreferences.getString("gameName","");

    User.getUser(username, new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            user.setValue(snapshot.getValue(User.class));

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

    Game.getGame(gameName, new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            game.setValue(snapshot.getValue(Game.class));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

public LiveData<User> getUser() {
    return user;
}

public LiveData<Game> getGame() {
    return game;
}

}

public class HomeFragment extends Fragment {

private HomeViewModel homeViewModel;
ListView listView;
RoomsAdapter roomsAdapter;
ArrayList<Room> arrayList;
Button btnOpen;
User currentUser;
Game chosenGame;
SharedPreferences gameSharedPreferences;
public String console,username,game;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_home, container, false);
    btnOpen = root.findViewById(R.id.btnOpen);
    listView = root.findViewById(R.id.lvRooms);
    arrayList = new ArrayList<>();
    roomsAdapter = new RoomsAdapter(getActivity().getApplicationContext(),arrayList);
    listView.setAdapter(roomsAdapter);

    gameSharedPreferences = getActivity().getSharedPreferences("game",0);

    SharedPreferences usernameSharedPreferences = getActivity().getSharedPreferences("users",0);
    username = usernameSharedPreferences.getString("username","");

    SharedPreferences consoleSharedPreferences = getActivity().getSharedPreferences("console",0);
    console = consoleSharedPreferences.getString("console","");

    game = gameSharedPreferences.getString("gameName","");
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);


    if (!game.equals(""))
    {
        chosenGame = new Game("fortnite",4,"");
    }else {
        homeViewModel.getGame().observe(getViewLifecycleOwner(), new Observer<Game>() {
            @Override
            public void onChanged(Game game) {
                chosenGame = game;
            }
        });
    }
    homeViewModel.getUser().observe(getViewLifecycleOwner(), new Observer<User>() {
        @Override
        public void onChanged(User user) {
            currentUser = user;
        }
    });

    setData();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            if (arrayList.get(position).getPassword() == null)
            {
                Intent intent = new Intent(getActivity(), SingleRoomActivity.class);
                intent.putExtra("room",arrayList.get(position));
                startActivity(intent);
            }else
            {
                final Dialog dialog = new Dialog(getActivity());
                dialog.setContentView(R.layout.dialog_enter_password);
                final EditText edEnterPassword = dialog.findViewById(R.id.edEnterPassword);
                Button btnJoin = dialog.findViewById(R.id.btnJoin);

                btnJoin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (edEnterPassword.getText().toString().equals(arrayList.get(position).getPassword()))
                        {
                            Intent intent = new Intent(getActivity(),SingleRoomActivity.class);
                            intent.putExtra("room",arrayList.get(position));
                            startActivity(intent);
                        }else
                        {
                            Toast.makeText(getActivity(), "wrong password", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                dialog.show();
            }


        }
    });

    btnOpen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.dialog_open_room);
            final EditText edRoomName = dialog.findViewById(R.id.edRoomName);
            final EditText edRoomPassword = dialog.findViewById(R.id.edRoomPassword);
            final Switch sPassword = dialog.findViewById(R.id.sPassword);
            Button btnCreate = dialog.findViewById(R.id.btnCreate);


            sPassword.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (sPassword.isChecked())
                    {
                        edRoomPassword.setEnabled(true);
                    }else
                    {
                        edRoomPassword.setEnabled(false);
                        edRoomPassword.setText("");
                    }
                }
            });

            btnCreate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Room room;
                    if (sPassword.isChecked())
                    {
                        room = new Room("",edRoomName.getText().toString(),chosenGame,edRoomPassword.getText().toString(),1,username);
                    }else
                    {
                        room = new Room("",edRoomName.getText().toString(),chosenGame,1,username);
                    }

                    Room.createRoom(room,console, new OnCompleteListener() {
                        @Override
                        public void onComplete(@NonNull Task task) {
                            if (task.isSuccessful())
                            {
                                room.addPlayerToRoom(currentUser, console, new OnCompleteListener() {
                                    @Override
                                    public void onComplete(@NonNull Task task) {
                                        if (task.isSuccessful())
                                        {
                                            Intent intent = new Intent(getActivity(),SingleRoomActivity.class);
                                            intent.putExtra("room",room);
                                            startActivity(intent);
                                            arrayList.add(room);
                                            roomsAdapter.notifyDataSetChanged();
                                        }else
                                        {
                                            Toast.makeText(getActivity().getApplicationContext(), "failed", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                            }else
                            {
                                Toast.makeText(getActivity().getApplicationContext(), "failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    dialog.dismiss();
                }
            });

            dialog.show();
        }
    });

    return root;
}



private void setData() {
    Room.getRooms(console,chosenGame,new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren())
            {
                Room room = dataSnapshot.getValue(Room.class);
                arrayList.add(room);
            }
            roomsAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...