Java, Generating a dynamic object name [duplicate] - java

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
I was trying to generate a dynamic object names that will change everytime an object is created. Something like:
first object name would be like "userName" and the following would be like "userName1".
I'm new to java, and I tried to initialize int count=0 and count++ to do it, but the User class doesn't seem to allow me to do that like userName+count. Therefore, is there anyway i could possible go about doing it?
I have search through all the similar thread about dynamic object name, but it doesn't seems to work out for my case.
EDIT
So i have this app built up, that allow user to create account.
And, now i encounter this problem where whenever i tried to create new account,
Firebase clear away all my previous data that i have inserted, and replace it with the current inserted data.
Here's my code:
Main.java
name = (EditText) findViewById(R.id.edit_rName);
email = (EditText) findViewById(R.id.edit_rEmail);
password = (EditText) findViewById(R.id.edit_rPassword);
Button btnSubmit = (Button) findViewById(R.id.btn_rSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Firebase f = new Firebase("https://xxx.firebaseio.com/");
Firebase usersRef = f.child("users");
Map<String, User> users = new HashMap<String, User>();
users.put(name.getText().toString(), new User(name.getText().toString(), password
.getText().toString(), email.getText().toString()));
usersRef.setValue(users);
}
});
User.java
public class User {
private String fullName;
private String password;
private String email;
public User(String fullName, String password,String email) {
this.fullName = fullName;
this.password = password;
this.email = email;
}
public String getPassword() {
return password;
}
public String getFullName() {
return fullName;
}
}

You should use an array if you know in advance how many objects you will create, and a list if you don't know in advance.
Array:
String[] usernames = new String[4];
usernames[0] = "Alex";
usernames[1] = "Bob";
usernames[2] = "Carol";
usernames[3] = "David";
//usernames[4] = "Eliza"; // won't work, out of bounds!
System.out.println(usernames[2]); //prints Carol
List(recommended) (first import java.util.ArrayList):
List<String> usernames = new ArrayList<String>();
usernames.add("Alex");
usernames.add("Bob");
usernames.add("Carol");
usernames.add("David");
usernames.add("Eliza");
System.out.println(usernames.get(2)); // prints Carol
usernames.set(2, "Carlos");
System.out.println(usernames.get(2)); // prints Carlos

Related

How can I get hashmap's key inside of the hashmap [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed last year.
I'm trying to make a system without MySQL database which will have accounts and accounts' data. But it didn't work
My accounts java file:
/*
* Instead of using 2 different ArrayList (for Username and Password) we used Hashmap
* HashMap stores keys and the keys' values
* In our HashMap keys refer to usernames values refer to passwords
*/
import java.util.HashMap;
import javax.swing.JOptionPane;
public class Accounts {
//I used static to reach list from another class suggest me another way please
static HashMap AccountList = new HashMap<String, HashMap<String, String>>();
public static void CreateAccount(String userID, String password, String email, String fullName, String department){
//We have to check that there shouldn't be an account with the same username
if (AccountList.containsKey(userID)){
JOptionPane.showMessageDialog(null, "There is an account with that username");
}
else{
HashMap Data = new HashMap<String, String>();
Data.put("userID", userID);
Data.put("password", password);
Data.put("email", email);
Data.put("fullName", fullName);
Data.put("department", department);
AccountList.put(userID, Data);
JOptionPane.showMessageDialog(null, "Member created successfully");
}
}
}
In my login.java I get an error on that line
boolean IsLoginSuccessful = false;
//We are getting username and password text/string from the form
String userID = username_field.getText();
String password = password_field.getText();
//Now check if username is in list then check if username's password equals to password
if (Accounts.AccountList.containsKey(userID)){
String userPassword = Accounts.AccountList.get(userID).get("password");
IsLoginSuccessful = true;
}
That second ".get" gives error like "cannot find symbol". Why does it take the hashmap as an object element? Also if you have another way to store these datas without hashtable and check the password etc. Show me please thank you.
To get the keys you would do
Set<String> keys = AccountList.keySet();
And you should declare your map as
Map<String, Map<String,String>> accountList = new HashMap<>();
Map<String,String> data = new HashMap<>();
But it would be best if you would declare a user class and put that in the map.
class User {
private String username;
private String password;
...
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
Map<String, User> accountList = new HashMap<>();
You could then use defined getters (e.g. user.getPassword(),
user.getUsername()) to retrieve the information.
Then it might be used as follows:
String username = get_from_console.
User user = accountList.get(username);
String password = user.getPassword();

Remove data that was previously added in App

Hello so I have this Java code for an address book app on android studio where I have the add button so whatever name I type, it gets added into the address book app. I made a delete button so whatever name I type in, if it is already added, it will delete it from the address book data. How would I get the delete button to work
public void btnAddData(View v)
{
String name= firstName.getText().toString();
String surName= lastName.getText().toString();
String phone1= phone.getText().toString();
Person person= new Person();
person.name=name;
person.surname=surName;
person.phone=phone1;
persons.add(person);
setTextToTextView();
}
public void btnRemoveData(View v)
{
//code to delete name
}
private void setTextToTextView()
{
String text = "";
for (int i=0;i<persons.size(); i++)
{
text=text + persons.get(i).name+","+persons.get(i).surname+","+persons.get(i).phone+"\n";
}
results.setText(text);
}
You would do this :-
persons.remove(<index or object name>);
You can find it using loop and then remove it.
public void btnRemoveData(View v)
{
String name= firstName.getText().toString();
for (int i=0;i<persons.size(); i++)
{
if(persons.get(i).name.equals(name)) persons.remove(i);
}
}

Access Variables From Other Class With Getter Setter JAVA

I'm getting problem with accessing variables with getter & setter on multiple classes. I looked up this one but I'm too confused.
I have 3 type users: Admin (Position No: 0 in mysql table), Manager (Position No: 1), Clerk (Position No:2).
I have SeeReportsAndFeedbacks class. I want to show all reports by selecting rows with position_no = 0 and 1 to admin and manager, 2 to clerk. It's already done with if statement.
So clerk can see only see reports that with position_no=2
manager can see only see reports that with position_no=0 and 1
admin can see only see reports that with position_no=0 and 1
Please help me. I'm stucked here for a long time. What are wrong with my getter setters?
If i set on Login_Form, and call get it shows correct in girisyap() function but if i call get in other class named SeeReportsAndFeedbacks it shows first initial value from Users () constructor instead of set value on girisyap() function on Login_Form.
tip value takes position_no from mysql db as string, new1 value is parsing (converting) string to int for if statement
screenshot
GIST
Users Class
public class Users {
private int id;
private String username;
private String fullname;
private String password;
private String phone;
private String gender;
private byte[] image;
private int position_no;
public Users () {
setPno(1); //firsst initialize
//getFullname();
}
public Users (int uid ,String uname, String fname, String upassword, String uphone, String ugender, byte[] uimage, int pno){
this.id = uid;
this.username = uname;
this.fullname = fname;
this.password = upassword;
this.phone = uphone;
this.gender =ugender;
this.image =uimage;
this.position_no = pno;
}
public Users (int pno){
setPno(pno);
}
public int getPno(){
return position_no;
}
public void setPno(int pno){
this.position_no = pno;
}}
SeeReportsAndFeedbacks class (i removed not-related funcs or some other gui things for the question.
public class SeeReportsAndFeedbacks { // extends javax.swing.JFrame
//CLIENT client = new CLIENT();
int new1 = 9999; //testing something
int PositionNoGetiren;
//sers loginf = new Users(0, null,null,null,null,null,null,new1);
public SeeReportsAndFeedbacks() {
//initComponents();
Users loginf = new Users();
PositionNoGetiren = loginf.getPno(); //gets initial value instead of set value on login_form
System.out.println("Babakingg " + PositionNoGetiren);
//int ananas = loginf.getPno();
//fillFeedbackJTable(jTable2);
}
public void fillReportJTable(){//JTable table
//loginf.setPno(2); it works if i manually set but it's useless
//System.out.println("Loginfvalue in see reports: " + loginf.getPno() + loginf.getUsername());
//new1 = loginf.getPno(); //not works shows 0
//see.getNo();
new1=PositionNoGetiren;
String selectQuery = "SELECT * FROM `users` WHERE `position_no` = ?";
if(new1==0){//admin
selectQuery = "SELECT * FROM `reports`";
}
if(new1==1){//manager
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 1";
}
if(new1==2){//clerk
selectQuery = "SELECT * FROM `reports` WHERE `position_no` = 2";
}
//}
}}
Login_Form
public class Login_Form {
int positionNoGetiren;
/**
* Creates new form Login_Form
*/
public Login_Form() {
//initComponents();
//positionNoGetiren = 9999;
}
private void girisyap() {
//I DELETED ALL DATABASE RELATED THINGS FOR QUESTION.
//String tip = rs.getString("position_no"); //DETECTS CORRECTLY POSITION NO FROM DATABASE
String tip = "IT'S rs.getString(\"position_no\")"; //for posting question
System.out.println(tip);
int new1 = Integer.parseInt(tip);
//Users loginf = new Users(new1); //welcome yazisi icin
Users loginf = new Users(); //ONLY WORKS IN THIS CLASS.
loginf.setPno(new1); //set user type for reports class BUT IT'S NOT WORKING
System.out.println("Loginf degeri login_formdaki: " + loginf.getPno());
//THIS IF IS WORKING CORRECTLY.
if(new1==0){
//Admin form = new Admin();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
if(new1==1){
//Manager form = new Manager();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
}
if(new1==2){
//Clerk form = new Clerk();
//form.setVisible(true);
//form.pack();
//form.setLocationRelativeTo(null);
// form.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
//this.dispose();
}
private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {
girisyap();}
}
There is nothing wrong with your getters and setters.
This is most likely an issue with parsing the value of TIP, that could not be parsed as an INT, maybe its a float with a weird value of like 2.00000004, or simply null. Try writing a test or log the value which your query return and check if this is the value you are looking for.

Android put data retrieved from Parcelable into an array

This is an extension of Android implement Parcelable objects with hashmap that contains another hashmap where I was having trouble passing 2 classes between activities using Parcelable.
I'm now able to successfully pass both classes together using Parcelable. However, I'm having trouble putting the retrieved data into an array list.
Here's the EventDetails class:
public class MatchedEvent implements Parcelable {
Private String eventId;
Private String eventName;
Private Long eventUnixTime;
Private Map <String, User> attendees = new HashMap<String, User>();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(eventId);
dest.writeString(eventName);
dest.writeLong(eventUnixTime);
final int N = attendees.size();
dest.writeInt(N);
if (N > 0) {
for (Map.Entry<String, User> entry : attendees.entrySet()) {
dest.writeString(entry.getKey());
User user = entry.getValue();
dest.writeString(user.getEmail());
dest.writeString(user.getUserName());
dest.writeString(user.getUserPicture());
}
}
}
protected MatchedEvent(Parcel in) {
eventId = in.readString();
eventName = in.readString();
eventUnixTime = in.readLong();
final int N = in.readInt();
for (int i = 0; i < N; i++) {
String key = in.readString();
User user = new User();
user.email = in.readString();
user.userName = in.readString();
user.userPicture = in.readString();
attendees.put(key, user);
}
}
public Map<String, User> getAttendees() {
return attendees;
}
Here's the User class:
public class User implements Parcelable {
public String email;
public String userName;
public String userPicture;
private Boolean hasLoggedInWithPassword;
private HashMap<String, Object> dateJoined = null;
}
public User(Parcel in) {
email = in.readString();
userName = in.readString();
userPicture = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(email);
dest.writeString(userName);
dest.writeString(userPicture);
}
Here's the Fragment to retrieve the data. The EventDetails class should return a few Users. My goal is to display the name of all Users in a TextView that lists out the names with a line break. I was able to retrieve the users in an array but was not able to create an array just for the userName.
public class EventDetailsFragment extends BaseFragment {
TextView attendees;
private Map<String, User> attendeeMap;
#Override
public void onCreate(Bundle savedInstanceState) {
MatchedEvent matchedEvent = getArguments().getParcelable("eventDetailsData");
attendeesMap = matchedEvent.getAttendees();
List<User> users = new ArrayList<>();
for (String key : attendeesMap.keySet()) {
User user = attendeesMap.get(key);
users.add(user);
Log.i("Attendees Details", String.valueOf(user)); //I was able to get all users in this log.
ArrayList<String> attendeesDetails = new ArrayList<>();
attendeesDetails.add(user.getEmail());
attendeesDetails.add(user.getUserName());
attendeesDetails.add(user.getUserPicture());
for (User user1 : users) {
Log.i("Attendees Details", String.valueOf(attendeesDetails)); //?????????????????
}
}
}
The problem is where i put the mark "//?????????????????".
I'm getting duplicate data. I know I shouldn't be putting a loop inside another loop. Can someone please advise how I can break this down? My goal is to put all the users' names in an array and display them in the TextView with a line break after each name.
This is what I got from the log:
I/Attendees Details: com.test.entities.User#f2b14s9
I/Attendees Details: [user1#gmail.com, Deric, https://dropbox.xxxxxx]
I/Attendees Details: com.test.entities.User#e6s26k2
I/Attendees Details: [user2#gmail.com, Jose, https://dropbox.xxxxxxxxx]
I/Attendees Details: [user2#gmail.com, Jose, https://dropbox.xxxxxxxxx]
I/Attendees Details: com.text.entities.User#b9k03l6
I/Attendees Details: [user3#gmail.com, Matt, https://dropbox.xxxxxxxxxxxxx]
I/Attendees Details: [user3#gmail.com, Matt, https://dropbox.xxxxxxxxxxxxx]
I/Attendees Details: [user3#gmail.com, Matt, https://dropbox.xxxxxxxxxxxxx]
I believe the reason why there are duplicate entries is because "attendeesDetails" is inside the loop “attendeesMap” where I got the key of each user. I’m not sure how to separate them but still able to get the data.
Thanks in advance for helping out.
-R
this will help you:
#Override
public void onCreate(Bundle savedInstanceState) {
EventDetails eventDetails = getArguments().getParcelable("eventDetailsData");
attendeesMap = eventDetails.getAttendees();
List<User> users = new ArrayList<>();
for (String key : attendeesMap.keySet()) {
User user = attendeesMap.get(key);
users.add(user);
Log.i("Attendees Details", String.valueOf(user)); //I was able to get all users in this log.
attendees.append(user.getEmail()+user.getUserName()+user.getUserPicture()+"\n");
}
I think I'd resolved the problem. I actually need to create an ArrayList<HashMap<String, String>> to store the details for each and every user first. Then, I'll be able to create another array list to store the names. No more nested loops.
List<User> users = new ArrayList<>();
ArrayList<HashMap<String, String>> userArrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> usersDetailsHashMap = new HashMap<String, String>();
ArrayList attendeesNames = new ArrayList();
for (String key : attendeesMap.keySet()) {
User user = attendeesMap.get(key);
users.add(user);
usersDetailsHashMap.put("name", user.getUserName());
usersDetailsHashMap.put("email", user.getEmail());
usersDetailsHashMap.put("picture", user.getUserPicture());
userArrayList.add(usersDetailsHashMap);
attendeesNames.add(userArrayList.get(0).get("name"));
}
Log.i("userNames", String.valueOf(attendeesNames));
This will return in the log:
[Deric, Jose, Matt]

How to convert a list of objects to a JSON object?

I have a HashSet of objects that I am trying to put on a JSON object.
HashSet<Users> users;
...
JSONObject j = new JSONObject();
j.put("users", users);
However,
System.out.println(j.toString(2));
is giving me
{"users": [
{},
{}
]}
when there are 2 entries in the HashSet. The non-null values of Users objects are not there.
Is there more to converting a List of a declared type to a JSONObject?
I am using the JSON at org.json.*.
The Users class is as follows:
public class Users {
byte[] pic;
String firstName;
String lastName;
String address;
}
I'm seeing the entries in the HashSet "users" fine every otherwise.
TIA.
The problem is with your Users class. You appear to be expecting it to just pick up the fields, but I don't believe JSONObject does that - instead, it finds bean-like getters.
If you try to convert a single instance of your Users class to a JSONObject you get exactly the same result ({}) - this problem has nothing to do with trying to convert multiple instances. (It would be worth taking a lesson from this about diagnosing problems - always try to reduce the scope.)
As soon as you create a class with appropriate getters, it works fine. Sample code:
public final class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
import org.json.*;
import java.util.*;
class Test {
public static void main(String [] args) throws Exception {
User user = new User("Jon", "Skeet");
JSONObject single = new JSONObject(user);
System.out.println("Single user: " + single);
Set<User> users = new HashSet<>();
users.add(new User("Jon", "Skeet"));
users.add(new User("Holly", "Skeet"));
JSONObject multiple = new JSONObject();
multiple.put("users", users);
System.out.println("Multiple users: " + multiple);
}
}
Output:
Single user: {"lastName":"Skeet","firstName":"Jon"}
Multiple users: {"users":[{"lastName":"Skeet","firstName":"Holly"},{"lastName":"Skeet","firstName":"Jon"}]}
I got correct result using the code below. Can you highlight if you are doing something different? Maybe I can make similar changes and try once.
public static void main(String[] args){
HashSet<String> users = new HashSet<>();
users.add("user1");
users.add("user2");
JSONObject j = new JSONObject();
j.put("users", users);
System.out.println(j.toString(2));
}
Output:
{"users": [ "user2", "user1" ]}
================================== EDIT =================================
I think I figured what the problem was. Please try the following code and let us know if that worked.
public static void main(String[] args) {
JSONObject o1 = new JSONObject();
o1.put("1", new User("User1"));
JSONObject o2 = new JSONObject();
o2.put("2", new User("User2"));
HashSet<JSONObject> users = new HashSet<>();
users.add(o1);
users.add(o2);
JSONObject j = new JSONObject();
j.put("users", users);
System.out.println(j.toString(2));
}
Using gson, it is much simpler.
Use the following code snippet:
// create a new Gson object
Gson gson = new Gson();
// convert your set to json
String jsonUsersSet = gson.toJson(users);
// print your generated json
System.out.println("jsonUsersSet: " + jsonUsersSet);
Convert from JSON string to your Java object:
// Converts JSON string into a set of user object
Type type = new TypeToken<Set<User>>(){}.getType();
Set<User> userSet = gson.fromJson(jsonUsersSet, type);
// print your Set<User>
System.out.println("userSet : " + userSet);

Categories