I previously asked the almost same question. But the answer wasn't that good or just not good enough. I wanted to start again and now I have a lot of problems.
Here is the post.
So for now I have another idea.
This time there is only one value which counts the votes, but the app don't get the actual amount of the value "count".
Here is my code:
database = FirebaseDatabase.getInstance();
names= database.getReference("Test");
final Name name = new Name(txtName.getText().toString(), score);
names.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
if (dataSnapshot.child(name.getName()).exists()) {
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
names.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
score = dataSnapshot.child("Test").child("Name").getValue(long.class);
score += 1;
final Name name = new Name(txtName.getText().toString(), score);
try {
names.child(name.getName()).setValue(name);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(Result.this, "Thank you for voting", Toast.LENGTH_SHORT).show();
Intent homeIntent3 = new Intent(Result.this, StartActivity.class);
startActivity(homeIntent3);
}
});
Here's the database
So if the name doesn't exist I easily can add the up/down vote with score = 1 or score = -1.
But if the name exists, there is a problem with changing the score value.
The app is crashing with the following error
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at user.prof.name.Activities.Result$1$1$1.onDataChange(Result.java:80)
at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.3:75)
at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0.3:63)
at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.3:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6589)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
And this is the error line in the code
score = dataSnapshot.child("Test").child("Name").getValue(long.class);
I'm not an expert in the database programming, but what is wrong? The wrong child?
I also tried to save the "score" as a String and parse it to a long value. But that's not also working.