0

this is the image of my database

In this project I am displaying scores from database. When I change the value of scores from the database it changes there but when I check in the app, it doesn't show the change there, and whenever the points gets added through rewarded video ad it doesnt show in the scores.

We need to restart the app to see the video ads point added, and when I change the values from database, it never shows on the app, I think its solution is easy and I am just a beginner.

public class Home_page extends AppCompatActivity implements RewardedVideoAdListener {

TextView score_text;
LinearLayout spin_button, logout_button, redeem_button, watch_video_buuton,share_id,rate_button;
;
private RewardedVideoAd mRewardedVideoAd;

int myIntValue;
DatabaseReference  user_id_child;
String user_id;
DatabaseReference databaseReference;





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);



    MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
    databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    user_id = mAuth.getCurrentUser().getUid();

    user_id_child = databaseReference.child(user_id);


    getSupportActionBar().setTitle("Earn Money");


    // Admob video ads
    MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544/5224354917");
    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    mRewardedVideoAd.setRewardedVideoAdListener(this);
    loadRewardedVideoAd();


    spin_button = (LinearLayout) findViewById(R.id.spin_linear_id);
    redeem_button = (LinearLayout) findViewById(R.id.linear_redeem_id);
    logout_button = (LinearLayout) findViewById(R.id.linear_logout_id);
    watch_video_buuton = (LinearLayout) findViewById(R.id.linear_watch_video_id);
    share_id = (LinearLayout)findViewById(R.id.linear_share_id);
    score_text = (TextView) findViewById(R.id.wallet_text_score_id);
   rate_button = (LinearLayout)findViewById(R.id.linear_rate_id);


    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    myIntValue = sp.getInt("your_int_key", 0);



    rate_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Uri uri = Uri.parse("https://www.instagram.com/dhruv__bhati/");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);

        }
    });








    watch_video_buuton.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View view) {

            if (mRewardedVideoAd.isLoaded()) {


                mRewardedVideoAd.show();
            }
       else {
                loadRewardedVideoAd();
                Toast.makeText(Home_page.this , "video ad not loaded ", Toast.LENGTH_LONG).show();
            }


        }
    });


    redeem_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Home_page.this, Redeem.class);

            startActivity(intent);

            overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
        }
    });

    logout_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            diaglog();
        }
    });


    spin_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(Home_page.this, Spinwheel.class);

            intent.putExtra("INT",myIntValue);

            startActivity(intent);


            overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
        }
    });


    share_id.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            share(view);
        }
    });

}





    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);//Menu Resource, Menu
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.logout_id: {
            logout();
        }

        return true;


    }


    return super.onOptionsItemSelected(item);


}

private void logout() {

    FirebaseAuth.getInstance().signOut();
    Intent intent = new Intent(Home_page.this, MainActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}




@Override
public void finish() {
    super.finish();


  finish();

}










@Override
public void onRewardedVideoAdLoaded() {
}

@Override
public void onRewardedVideoAdOpened() {

}

@Override
public void onRewardedVideoStarted() {

}

@Override
public void onRewardedVideoAdClosed() {

    loadRewardedVideoAd();

}

@Override
public void onRewarded(RewardItem rewardItem) {

    Toast.makeText(Home_page.this,"Congratulations, you will get 1000 points next time you open the app ", Toast.LENGTH_LONG).show();

    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();

    int n =  myIntValue+1000;
    editor.putInt("your_int_key", n);
    editor.commit();
    user_id_child.child("scores").setValue(+n);


    watch_video_buuton.setEnabled(false);

    final long startTime= Calendar.getInstance().getTime().getTime();
    final Timer timer=new Timer();
    TimerTask task=new TimerTask() {
        @Override
        public void run() {
            long curentTime=Calendar.getInstance().getTime().getTime();
            long elapsedTime=curentTime-startTime;
            ToastTime(10*60*1000, elapsedTime);
            if(curentTime-startTime>=10*60*1000){  //10 minutes in millisecond
                timer.cancel();
                watch_video_buuton.setEnabled(true);
            }
        }
    };
    timer.schedule(task, 500, 2000);




}

@Override
public void onRewardedVideoAdLeftApplication() {

}

@Override
public void onRewardedVideoAdFailedToLoad(int i) {

}

private void loadRewardedVideoAd() {

    if(!mRewardedVideoAd.isLoaded()){
    mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
            new AdRequest.Builder().build());


    }
}

@Override
public void onResume() {
    mRewardedVideoAd.resume(this);
    super.onResume();
}

@Override
public void onPause() {
    mRewardedVideoAd.pause(this);
    super.onPause();
}

@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(this);
    super.onDestroy();
}










@Override
protected void onStart() {
    super.onStart();

    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    myIntValue = sp.getInt("your_int_key", 0);

    String s = String.valueOf(myIntValue);
    score_text.setText(s);

    loadRewardedVideoAd();


}


public void share(View view){


    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Earn Money");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Earn unlimited money by simple tasks"+"  "+"https://play.google.com/store/apps/details?id=wheel.top.best.online.money.make.techyunk.com.earningwheel");
    startActivity(Intent.createChooser(sharingIntent, "Share via"));



}
public void diaglog(){


    final Dialog dialog = new Dialog(Home_page.this);
    dialog.setContentView(R.layout.custom_logout);
    Button no = (Button) dialog.findViewById(R.id.no_id);

    Button yes = (Button)dialog.findViewById(R.id.yes_id);

    // if button is clicked, close the custom dialog
    no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();


        }
    });

    yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            logout();
        }
    });

    dialog.show();

}

private void ToastTime(long totalTime, long elapsedTime) {
    final int remainInSec = (int) (totalTime - elapsedTime) / 1000;
    if (remainInSec > 0) {
        final Activity activity = this;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(activity, String.valueOf(remainInSec) + " seconds to enable video button", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

}

1 Answer 1

1

As I can see you didn't attach any listener to the Firebase, in your case you need to use addChildEventListener : ChildEventListener.

Be careful and only call this listener once in the onCreate method, If you call it more than once it attaches a new listener then you have two listeners and duplicated data.

UPDATE:

This is the user class you get from the firebase :

public class User {
    private String email;
    private String name;
    private String scores;

    public User() {
    }

    public User(String email, String name, String scores) {
        this.email = email;
        this.name = name;
        this.scores = scores;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getScores() {
        return scores;
    }

    public void setScores(String scores) {
        this.scores = scores;
    }
}

Now let's fetch the data :

firebaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
              // Here you can handle the new added items.
              // if you added a new user you will see it here
                User user = dataSnapshot.getValue(User.class);
              // Now For example let's log the result
                Log.d(TAG, "the user score is : " + user.getScore());
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
             // If you change the score this will appear here : 
                 User user = dataSnapshot.getValue(User.class);
             // Here is the new score you can use to update the score in the view
                 String score = user.getScore();

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

Now go and try this and you will get it.

7
  • please can you tell how i should do it in my case , in my code Oct 20, 2018 at 9:32
  • I have just edited my answer with the code, I hope it help you @dhruvbhati Oct 20, 2018 at 9:41
  • i didnt understood what to change , can you please provide a code looking at my main activity , i want the scores from my database get refreshed and show on the screen . please provide a code looking to my activity , please this will help me a lot , please Oct 20, 2018 at 10:33
  • Please show me your database and the type of the data you get from the firebase and want to represent and the view where you display the data ? because all of these information is not clear from the code you've written. Oct 20, 2018 at 11:26
  • see i have added a screenshot of my database in the question , i have provided the whole activity in the question , score_text is where i am providing the points from database Oct 20, 2018 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.