How i can update this Setlist of users? - java

I need some help guys. I'm making a chat who read an XML each 10 sec aprox (yeah the database is the XML, congrats my teacher, we can't change database format xDD)
So on, my question now i create the function, replace the messages is easy, if the xml messages are more than RAM one, then i clear the ram and then add all messages again, but i can't do that to users, i don't know why but i think equals or something is broken(? i don't know pls help me my brain is about to break!
if (temp.getList().size() > roomList.getList().size()) {
for (Room room_xml : temp.getList()) {
if (roomList.addRoom(room_xml)) {
System.out.println("A room was loaded");
}
}
} else {
for (Room room_xml : temp.getList()) {
for (Room room_ram : roomList.getList()) {
if (room_ram.equals(room_xml)) {
if (room_ram.getMessageList().size() < room_xml.getMessageList().size()) {
room_ram.getMessageList().clear();
room_ram.getMessageList().addAll(room_xml.getMessageList());
}
Set<User> us_xml = room_xml.getUserList();
for(User u_xml: us_xml){
for(User u_ram: room_ram.getUserList()){
if(room_ram.getUserList().add(u_xml)){
System.out.println("User was added(?");
}
}
}
/*for (User u_xml : room_xml.getUserList()) {
if(room_ram.getUserList().add(u_xml)){
System.out.println("User was added(?");
}else{
break;
}
}*/
I share my proyect on github if u need more info about that : https://github.com/Varo95/ChaTerra
This code is on RoomListDAO.java
PD: I put print but i use javafx xd
I got another idea, like declaring actual_user on roomdao and check on xml is on the list to add one....but doesn't seems to work :(

I already resolve it, thanks any way, i already do this and seems to work:
RoomList temp = load();
if (temp.getList().size() > roomList.getList().size()) {
for (Room room_xml : temp.getList()) {
if (roomList.addRoom(room_xml)) {
System.out.println("Room was loaded on RAM");
}
}
} else {
for (Room room_xml : temp.getList()) {
for (Room room_ram : roomList.getList()) {
if (room_ram.equals(room_xml)) {
if (room_ram.getMessageList().size() < room_xml.getMessageList().size()) {
room_ram.getMessageList().clear();
room_ram.getMessageList().addAll(room_xml.getMessageList());
}
room_ram.getUserList().clear();
room_ram.getUserList().addAll(room_xml.getUserList());
}
break;
}
}
}
saveFile(roomList);
And saving it too when user left the room or join but i need to make some little fixes more hahahaha well now i feel good with myself

Related

Finding which item(s) in a list is not present in the Realm

I am using the latest Java Realm local database backing a mobile app.
I have a Profile class and a Contact class in the app. Each Profile object can be associated with one or more Contact objects.
Upon startup, I want to reconcile against a similar Profile/Contact list on my website to insure that the mobile app is using the latest/greatest definition of the Profile/Contact relationship.
After validating the Profile during login, I then query the website to get the list of Contact email addresses associated with the Profile. I now need to do the following:
For each Contact email address in the list from the website, make sure that the local Realm Contact object shows as "connected" to the Profile object.
For each Contact object NOT in the list from the website, make sure that the local Realm Contact object shows as "not connected" to the Profile object.
So what I'm doing is after login, executing an AsyncTask that:
try {
realm.beginTransaction();
RealmResults<Contact> contactResults;
contactResults = realm.where(Contact.class).findAll();
if ( contactResults.size() == 0 ) {
// Nothing to do
return false;
}
// First set everything as not connected, then set only those passed in as connected
contactResults.setBoolean(IS_CONNECTED, false);
// Now update just the email addresses passed in as connected
contactResults = realm.where(Contact.class).in(EMAIL_ADDRESS, emailList.toArray(new String[0])).findAll();
if ( contactResults.size() > 0) {
contactResults.setBoolean(IS_CONNECTED, true);
}
//TODO - what if an item passed in is not yet in Contact list?
success = true;
} catch (Exception e) {
Timber.d("Exception resetting contacts status: %s", e.getMessage());
} finally {
if (success) {
realm.commitTransaction();
} else {
realm.cancelTransaction();
}
}
How I've done the first two pieces of work seem ok to me - as this app won't be scaling to thousands of "friends", resetting the contact to FALSE for everyone then to TRUE for the current set retrieved from the website is doable.
However, the third piece has me stumped - is there a single call I can make to identify which, if any, of the email addresses in the passed array aren't actually in my Contact object RealmResults and therefore need to be added as new objects?
Seems inefficient to loop through that list and check each one, one at a time, particularly since I've already performed two queries.
The only solution I've come up with so far is this:
try {
realm.beginTransaction();
fullContactResults = realm.where(Contact.class).findAll();
if ( fullContactResults.size() > 0 ) {
// First set everything as not connected, then set only those passed in as connected
fullContactResults.setBoolean(IS_CONNECTED, false);
}
// Now for each item in the list we were passed in find it and update it, or add it.
for ( String data : contactData ) {
Contact c = null;
String[] contactStruct = data.split(BODY_COMPONENTS_SEPARATOR);
RealmResults<Contact> partialContactResults = realm.where(Contact.class)
.equalTo(EMAIL_ADDRESS, contactStruct[CONNECTION_EMAIL_ELE])
.findAll();
if (partialContactResults.size() > 0 ) {
c = partialContactResults.first();
} else {
// Need to add the contact
c = realm.createObject(Contact.class, UUID.randomUUID().toString());
}
c.setConnected(true);
c.setDisplayName(contactStruct[CONNECTION_FIRSTNAME_ELE] + " " + contactStruct[CONNECTION_LASTNAME_ELE]);
c.setEmailAddress(contactStruct[CONNECTION_EMAIL_ELE]);
}
success = true;
} catch (Exception e) {
Timber.d("Exception resetting contacts status: %s", e.getMessage());
} finally {
if (success) {
realm.commitTransaction();
} else {
realm.cancelTransaction();
}
}
Which does a loop and either updates or inserts.
Any better way?

Why i get result.get(CaptureResult.CONTROL_AF_STATE); == INACTIVE?

I work with camera2API on Samsung S5 and if i try get state of focus i get value 0 which is equals to CaptureResult.CONTROL_AF_STATE_INACTIVE...
There is snip of code :
private void process(CaptureResult result) {
switch (mState) {
case CameraHelper.STATE_PREVIEW: {
// We have nothing to do when the camera preview is working normally.
here i get ---> Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (CaptureResult.CONTROL_AF_TRIGGER_START == afState) {
if (areWeFocused) {
Log.e("---!!! HERE !!!--- :", String.valueOf(areWeFocused));
}else {
}
}
if (CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED == afState) {
areWeFocused = true;
} else {
areWeFocused = false;
}
break;
}
But i also tried to test it on my Meizu MX5 and i get 1 - CaptureResult.CONTROL_AF_TRIGGER_START or 2 - CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED
Question is : what is the difference in my code? Why do i get 0 in one case and 1 or 2 in another?
I know this is an old question, but i just ran into the same issue. Read through the Android docs about ControlAfState (AF = Auto Focus for those who are unaware, like I was). If AutoFocus Mode (afMode) is set to AF_MODE_OFF you will get the ControlAfState of Inactive.
Android CaptureResult.CONTROL_AF_STATE

Bukkit Custom Prefix plugin doesn't work with Essentials

I'm making a plugin that will have ranks in the near future, but I decided to get past prefixes first. I have this code:
Essentials ess = (Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
User user = ess.getUserMap().getUser(p.getName());
//nickname
String nick = user.getDisplayName();
String prisoner = ColourMsg("&5<<&bPrisoner&5>>&r>" + " <");
p.setDisplayName(prisoner + nick);
For some reason, this code doesn't work! It only displays the nickname, and not the prefix (I would expect it to display both). Also, the only error message I get is from essentials chat, which isn't needed for my plugin and /nick still works.
If anyone can help, please let me know.
Thanks in advance!
You don't need Essentials for that (Essentials is a bad plugin anyway, since 1.8).
You can simply use scoreboard prefixes/suffix in the PlayerJoinEvent to set the tags.
Scoreboard sb = Bukkit.getScoreboardManager().getNewScoreboard();
Objective ob = sb.registerNewObjective("objName", "dummy");
public void onEnable() {
// Set Display slot
ob.setDisplaySlot(DisplaySlot.PLAYER_LIST);
}
public void onJoin(PlayerJoinEvent e) {
// Delay a task
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
if (e.getPlayer().hasPermission("tags.example")) {
sb.registerNewTeam("Example");
Team team = sb.getTeam("Example");
team.setPrefix(ChatColor.RED + "[Example]");
team.addEntry(e.getPlayer().getName());
} else if (e.getPlayer().hasPermission("tags.otherTag")) {
sb.registerNewTeam("OtherTag");
Team team = sb.getTeam("OtherTag");
team.setPrefix(ChatColor.GREEN + "[OtherTag]");
team.addEntry(e.getPlayer().getName());
}
}
}, 20 * 1); // The 1 is the number of seconds to delay, 1 is fine
}

Android: Parse.com concurrency issue with findInBackground()

I am using Parse.com as a backend for my app. The local database from Parse seems to be very easy to use, so I decided to use it.
I want to create a database with Name and PhoneNumber. That is easy, just make a new ParseObject and pinInBackground(). But it is more complicated when I want to remove duplicate numbers. First I need to search if the number already exists in the database and then add the new number if it doesn't exists.
The method to do this is:
public void putPerson(final String name, final String phoneNumber, final boolean isFav) {
// Verify if there is any person with the same phone number
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseClass.PERSON_CLASS);
query.whereEqualTo(ParseKey.PERSON_PHONE_NUMBER_KEY, phoneNumber);
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> personList,
ParseException e) {
if (e == null) {
if (personList.isEmpty()) {
// If there is not any person with the same phone number add person
ParseObject person = new ParseObject(ParseClass.PERSON_CLASS);
person.put(ParseKey.PERSON_NAME_KEY, name);
person.put(ParseKey.PERSON_PHONE_NUMBER_KEY, phoneNumber);
person.put(ParseKey.PERSON_FAVORITE_KEY, isFav);
person.pinInBackground();
} else {
Log.d(TAG, "Warning: " + "Person with the number " + phoneNumber + " already exists.");
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
}
);
}
Lets say I want to add 3 persons in the database:
ParseLocalDataStore.getInstance().putPerson("Jack", "0741234567", false);
ParseLocalDataStore.getInstance().putPerson("John", "0747654321", false);
ParseLocalDataStore.getInstance().putPerson("Jack", "0741234567", false);
ParseLocalDataStore.getInstance().getPerson(); // Get all persons from database
Notice that first and third person have the same number so the third souldn't be added to database, but...
The logcat after this is:
12-26 15:37:55.424 16408-16408/D/MGParseLocalDataStore: Person:0741234567 was added.
12-26 15:37:55.424 16408-16408/D/MGParseLocalDataStore: Person:0747654321 was added.
12-26 15:37:55.484 16408-16408/D/MGParseLocalDataStore: Person:0741234567 was added.
12-26 15:37:55.494 16408-16408/D/MGParseLocalDataStore: Person database is empty
The last line from logcat is from the method that shows me all persons from database:
public void getPerson() {
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseClass.PERSON_CLASS);
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> personList,
ParseException e) {
if (e == null) {
if (personList.isEmpty()) {
Log.d(TAG, "Person database is empty");
} else {
for (ParseObject p : personList) {
Log.d(TAG, p.getString(ParseKey.PERSON_PHONE_NUMBER_KEY));
}
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
}
So there are 2 problems:
The third number is added even if I checked if already exists.
The method that shows me all persons tell me I have nothing in my database even if in logcat I can see it added 3 persons.
I think the problem is findInBackground() method that does all the job in another thread.
Is there any solution to this problem?
Both of your problems are a result of asynchronous work. If you call the putPerson method twice, they will both run near-simultaneously in separate background threads and both find-queries will most likely return almost at the same time, and definitely before the first call has saved the new person.
In your example, the getPerson call will return before the background threads have been able to save your three people as well.
Your problem is not really related to Parse or localDataStore, but is a typical concurrency issue. You need to rethink how you handle concurrency in your app.
As long as this is only a local issue, you can impose synchronous structure with i.e. the Bolts Framework (which is already a part of your app since you're using Parse). But if calls to addPerson is done in multiple places, you will always face this problem and you'd have to find other solutions or workarounds to handle concurrency.
Concurrency is a big topic which you should spend some time studying.

Trying to get program to repeat

The program checks to see if the email address entered contains a # and a .edu
if it doesn't it needs to go back through the steps, I think I can use a do-while,but I haven't got one to work yet, how would I nest my if-else statements in a do-while? Thanks!
if (UserEmail.contains("#")) {
if (UserEmail.contains(".edu")){
System.out.print("Please create a password: ");
PassWord = kb.nextLine();
System.out.println(UserEmail.replaceAll("#\\S+?\\.edu\\b", ""));
System.out.print("Your password is " + PassWord);
} else {
System.out.print("email is not valid Please, try again.")
} else {
System.out.print("email is not valid Please, try again.");
// at this point it should repeat and ask for the email again
}
}
Define method isValid(String email, String password,... some more params) aand put all your check logic in the method.
Write something like this
while (!isValid(the params)) {
//ask all the credentials
}
to simplify your if-else code consider using
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
}
this can be wrappped in a do - while
do {
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
break;
}
System.out.print("email is not valid Please, try again.")
}
while (true);
You can simply add something like boolean correctEmail = false before your logic and at the beginning of your if statements, you write while(!correctEmail) {
At the end of your password-creation you set correctEmail to true and you're ready to go.
It is pretty straight forward.
bool trigger = (true/false);
do {
if (...) {
if (...){...}
else if (...) {...}
else {
print out retry statement;
trigger = false;
}
}
}
while (trigger == true);
Don't forget a semicolon at the end.

Categories

Resources