Java Getters/Setters - java

I'm creating a new instance of nPlayer for each user that connects to my server.
nPlayer nPlayer = new nPlayer(player);
The nPlayer class contains the following with a bunch of other methods used to grab the private variable details.
private Player player;
private boolean muted;
private boolean admin;
private boolean mod;
private boolean pvp;
public nPlayer(Player player) {
player = player;
muted = false;
admin = false;
}
example of method to grab variable details within the nPlayer class.
public boolean getAdmin() {
return admin;
}
I was wondering how do I go about grabbing say the admin variable from Nplayer of a specific user from another class?

You create an instance with
nPlayer nplayer = new nPlayer();
"nplayer" is the name of the variable, choose one you like. You have to save the data of this instance somewhere if you want to access the data upon reopening the program.
If you have the instance there (in this case 'nplayer'), you access the data like that:
boolean b = nplayer.getAdmin();
I should mention that you generally write class names always with the first letter capital, that would be "NPlayer".

It's sort of hard to understand exactly what your saying, but I'm assuming your asking about how to get information about the Player that is stored in nPlayer.
Get the player associated with nPlayer.
public Player getPlayer(){
return player;
}
A way to get details about the player
public String getPlayerName(){
return player.getName();
}
EDIT:
Let me get this right you want to be able to get a players, lets call it network state from other methods in your game. I think you are just organizing your code incorrectly. Instead of attaching a Player to nPlayer why don't you just store the network state of the player on top of the player? This way you can just load in you can just store all the information in player and be able to access it wherever you want.
Class Player {
NetworkState network;
public void connectPlayer(NetworkState network){
this.network = network;
}
public boolean isAdmin(){
return network.isAdmin();
}
....
}

When a user connects, create an instance of nPlayer and attach it to the session. Then when needed, just retrieve the object form the session and access its variables through the setters and getters.
How to store objects in the session: How do you store Java objects in HttpSession?

For starters: Do not store Player instance. Store their UUID to prevent memory leaks.
Actual solution:
You shouldn't use the class name as a field name, since the compiler might confuse a static method for the instance, and two, that's why class names start with a capital letter.
When you fix that, you can use the instance name .getAdmin() to get the boolean. You can insert that into an if check and perform something if it returns true.

Related

How do I pass current logged in user information across my application

I'm new to Programming and Java and building a small Application in JAVA with SQL and UI(Jframes)
In the log-in frame after the user enters his user name and password I do a SQL select query to search USER table for this user. If the query returns 1 single row, the login button event handler triggers and the object of the next frame is created.
few frames later I have an SQL insert activity where I also have to insert the USER_ID of the person initiating the insert(the current logged in user).
What is the best practice to pass this information across a series of frame classes?
My initial idea is to pass the user_id as a parameter in the object so it gets set in the constructor of each frame class. but the problem is not all my frames really need this data. Only the final frame involved with the insertion needs the user ID. but in-order to get to that frame I have to pass through all other frames.
This doesn't seem like a good practice.
First Approach
The first possibility I thought of was to use java.util.Properties to store the application state inside of a properties file. The approach would be to use a singleton wrapper, let's say ApplicationState for reading/writing to properties file. This singleton class would be reachable from all frames, alternatively an instance of this class could be passed inside of constructor.
public class ApplicationState {
private static ApplicationState instance = new ApplicationState();
private ApplicationState() { }
public static ApplicationState getInstance( ) { return instance; }
public String read(String key) throws IOException {
try (InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
prop.load(input);
return prop.getProperty(key);
}
}
...
}
Second Approach
Then I realized that a much cleaner solution would be to use the java.util.prefs.Preferences API. See Preferences API for details.
class A {
public void login() {
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
prefs.putInt("userId", 11);
...
}
}
class B {
public void insert() {
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
int userId = prefs.getInt("userId", 0); // 0 is default identifier
...
}
}
In addition because you want to store sensitive information, encrypted storage would be useful. For using encrypted preferences see this article.

Accessing objects that have already been created of the same class Android

So I am creating a chat app for android and I'm using Java and I need some help wrapping my head around some things. Whenever the user first registers, I am creating a new object of a class named User. When they enter the next layout, I need to access that objects data.
public class User {
public String username;
public User() {}
public User(String username) {
this.username = username;
}
public String getUsername(){
return username;
}
}
This is my User class. When they send a message, I need to be able to grab their username from this User object from an entirely different method without passing the object through a parameter. I can't seem to wrap my head around how to access their information and none of my methods seem to work. Any help is appreciated
If you do
User myUser = new User();
the variable myUser contains a reference to the newly created object. You must keep this reference around in order to later access the object. How exactly you do this depends on the logic of your program. Sometimes you would keep it in a field of another object or pass it around as parameter. For example
un = myUser.getUsername();
or
void myMethod(User theUser) {
...
String un = theUser.getUsername();
}
...
// call the method passing the user reference
myMethod(myUser);
in the main class make the data object... static
public static Model obj;
obj= new Model();
then from other class access it with your class name
example
main.obj;
I solved this issue by just using SharedPreferences. I stored the username associated with the key of each user. This way, I can always search the username for each user.

Pattern for persisting data in Realm?

My issue is how to organize the code. Let say I have a User class
public class User extends RealmObject {
#PrimaryKey
private String id;
#Required
private String name;
public User() { // per requirement of no args constructor
id = UUID.randomUUID().toString();
}
// Assume getter & setter below...
}
and a Util class is needed to handles the save in an asynchronous manner since RealmObjects cannot have methods other than getter/setter.
public class Util {
public static void save(User user, Realm realm) {
RealmAsyncTask transaction = realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealm(user); // <====== Argument needs to be declared final in parent method's argument!
}
}, null);
}
}
The intention is to put save() in a Util class to prevent spreading similar save code all over the code-base so that every time I wanted to save I would just call it as such:
User u = new User();
u.setName("Uncle Sam");
Util.save(u, Realm.getDefaultInstance());
Not sure if this affects performance at all, but I was just going to save all fields overwriting what was there except for the unique id field every single time.
The problem is that I now need to set the "user" argument as final in the Util.save() method, which means I cannot pass in the object I need to save other than once.
Is there a different way of handling this? Maybe a different pattern? Or am I looking at this all wrong and should go back to SQLite?
Why is it a problem to set public static void save(final User user, Realm realm) ? It just means you cannot reassign the user variable to something else.
That said, the existence of a save() method can be a potential code smell as you then spread the update behaviour across the code base. I would suggest looking into something like the Repository pattern (http://martinfowler.com/eaaCatalog/repository.html) instead.
Realm is actually working on an example showing how you can combine the Model-View-Presenter architecture with a Repository to encapsulate updates which is a good pattern for what you are trying to do here. You can see the code for it here: https://github.com/realm/realm-java/pull/1960

How do I pass an object created in one class to another in java?

I'm trying to develop an online hotel booking system. I have the main class which takes input from the user such as their name, their payment information, and other data fields and makes a Reservation object using that information. I have another class called Room that has a list of Reservations for each Room object. The problem I am having is I can't figure out a way to add the Reservation object into the list in the Room object. Here is some of the code:
public class HotelReservationSystem
{
private Reservation reservation;
public void makeReservation(int checkIn, int checkOut)//Other parameters
{
reservation = new Reservation(checkIn, checkOut);
}
}
public class Room
{
private ArrayList<Reservation> reservations;
public void addReservation(//parameters?)
{
reservations.add(//parameter?);
}
}
I don't know how to get the new Reservation object to be passed as a parameter for the add method in the Room class.
I just can't wrap my head around it and was hoping for someone to help jog my thinking process.
Thanks for your help.
Let makeReservation return the created Reservation object:
public Reservation makeReservation(int checkIn, int checkOut)//Other parameters
{
reservation = new Reservation(checkIn, checkOut);
return reservation;
}
(You could also create a getter for reservation)
Then change your addReservation like this:
public void addReservation(Reservation res)
{
reservations.add(res);
}
And then just add it like this:
HotelReservationSystem hrs = new HotelReservationSystem();
Reservation res = hrs.makeReservation();
Room room = new Room();
room.addReservation(res);
However, you might want to rethink your model. Right now your HotelReservationSystem is creating a reservation and only saves that one, overwriting old ones. What happens if you create more than one? Also how can you get the reservations for a certain room given the HotelReservationSystem object? Just some things to think about...
I believe you must have tried this
public void addReservation(Reservation reservation)
{
reservations.add(reservation);
}
but the problem here is that your list reservations is null and will throw null pointer exception. So better initialize it at declaration. So change this
private ArrayList<Reservation> reservations;
to
private ArrayList<Reservation> reservations = new ArrayList<Reservation>();
And in your makeReservation method of Hotel class do this:
Room room = new Room();
room.addReservation(reservation);

Scope of object within an object in Java

I'm learning Java at the moment so I hope this question isn't too obvious. I come from another language which does not have garbage collection.
In this other language I sometimes created objects in constructor and then deleted them in the destructor so I could use them for the entire life of the object.
As a simplified example, I have a user and a booking class. The booking class references a user but if I create the user in the constructor of the booking class, it dereferences the user once it leaves the constructor and becomes out of scope. Any future reference call to the booking.bookedBy user then returns null.
class user {
public String username;
public String displayName;
user(Connection conn, String usernameIn){
username = usernameIn;
... do DB stuff to populate attributes
}
}
class booking {
int bookingID;
user bookedBy;
...
booking(Connection conn, int bookedIDIn){
bookingID = bookedIDIn;
...do DB stuff to populate attributes and grab bookedByUserID
...field value and build the BookedByUsername
user bookedBy = new user (bookedByUsername)
}
}
Is there a way around this? Or do I need to rethink my design?
You are creating a new bookedBy user variable in your constructor, rather than using your class' member variable.
You probably want to change:
user bookedBy = new user(bookedByUsername);
with:
bookedBy = new user(bookedByUsername);
You're declaring a local variable in your constructor and it's being used to assign the user you create in the constructor.
I think you want this:
class booking {
int bookingID;
user bookedBy;
...
booking(Connection conn, int bookedIDIn){
bookingID = bookedIDIn;
//there's no declaration of type needed here because
//you did that earlier when you declared your member variable up top.
bookedBy = new user (bookedByUsername)
}
}
In your booking class, you actually have declared two variables called user bookedBy. One has scope for the entire booking class and one has scope for the constructor. To fix this problem, you need to remove the variable declaration in your constructor as show below:
class booking {
int bookingID;
user bookedBy;
...
booking(Connection conn, int bookedIDIn){
bookingID = bookedIDIn;
...do DB stuff to populate attributes and grab bookedByUserID
...field value and build the BookedByUsername
bookedBy = new user (bookedByUsername)
}
}
user bookedBy;
and
user bookedBy = new user (bookedByUsername)
are two different variables.
Remove the second type declaration and your user instance will be allocated to the field level. ie:
class booking {
int bookingID;
user bookedBy;
...
booking(Connection conn, int bookedIDIn){
bookingID = bookedIDIn;
...do DB stuff to populate attributes and grab bookedByUserID
...field value and build the BookedByUsername
bookedBy = new user (bookedByUsername)
}
}

Categories