setText on Buttons not working while on TextView working - java

This is my Firebase Database Structure:
enter image description here
I'm fairly new to Java and trying to figure out how to solve this.
So I am making a Quiz app till now everything works fine except I cant retrieve data from Firebase RealTime Database.
My layout:
I have a textView to display the question
4 Buttons to display the options that the user can choose from
When the user clicks on a Button it either the Button Color turns to Red or Green depending on the question answer if it was correct or no.
I added one more textView for the timer which is neglected for no
I can only retrieve data for the Question textView but the buttons does not show anything
My Question Class:
package com.example.android.quizapp;
public class Question
{
public String question,option1,option2,option3,option4,answer;
public Question(String question,String option1,String option2,String option3,String option4,String answer)
{
this.question=question;
this.option1=option1;
this.option2=option2;
this.option3=option3;
this.option4=option4;
this.answer=answer;
}
public Question()
{
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
public String getOption3() {
return option3;
}
public void setOption3(String option3) {
this.option3 = option3;
}
public String getOption4() {
return option4;
}
public void setOption4(String option4) {
this.option4 = option4;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
My questions java activity class:
package com.example.android.quizapp;
import android.app.VoiceInteractor;
import android.graphics.Color;
import android.graphics.Path;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class questions extends AppCompatActivity
{
TextView txtquestions,timer;
Button OptionA,OptionB,OptionC,OptionD;
int total=0;
int correct=0;
int wrong=0;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
txtquestions=(TextView)findViewById(R.id.Questions);
OptionA=(Button)findViewById(R.id.OptionA);
OptionB=(Button)findViewById(R.id.OptionB);
OptionC=(Button)findViewById(R.id.OptionC);
OptionD=(Button)findViewById(R.id.OptionD);
timer=(TextView)findViewById(R.id.timer);
updateQuestions();
}
private void updateQuestions()
{
total++;
if(total>2)
{
//open the result activity
Toast.makeText(questions.this,"Done",Toast.LENGTH_SHORT).show();
}
else
{
reference=FirebaseDatabase.getInstance().getReference().child("questions").child(String.valueOf(total));
reference.addValueEventListener((new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
final Question question=dataSnapshot.getValue(Question.class);
txtquestions.setText(question.getQuestion());
OptionA.setText(question.getOption1());
OptionB.setText(question.getOption2());
OptionC.setText(question.getOption3());
OptionD.setText(question.getOption4());
OptionA.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionA.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionA.setBackgroundColor(Color.RED);
if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the question
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionB.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionB.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionB.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionC.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionC.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionC.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionD.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionD.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionD.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
}));
}
}
}
I only expect for the Buttons to be able to display data from Firebase database and the colors to work correctly because right now they all turn red when pressed
Problem solved I just needed to import a JSON file into my Database instead of creating it from Firebase Database

Don't know this issue but you can simply do get value in string than you can use the string variable for set Text. like that:
String A, B, C, D;
A = question.getOption1();
B = question.getOption2();
C = question.getOption3();
D = question.getOption4();
OptionA.setText(A);
OptionB.setText(B);
OptionC.setText(C);
OptionD.setText(D);
Just a Suggestion It will be work for you.

Are you sure that the options retrieved from database have values?
As you do not provide more details in your code that retrieves data from Database check if your options have values with :
Log.i("OptionA value: ", question.getOption1());
Check your logcat and tell us what you see.
It seems that the text for you OptionButtons is null. It is normal that all buttons turn red because the answer is compared with null.

Related

How can you wait between two events in java?

I am creating a trivia app. I want the right/wrong animation to occur immediately after the user clicks an answer, and then after 3 seconds, the question to switch automatically(fading into the next question). I tried doing this using Thread.sleep(3000), but the whole program freezes. This is my code so far:
binding.buttonTrue.setOnClickListener(view -> {
checkAnswer(true);
updateQuestion();
//these two calls invoke right/wrong animation
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeTheQuestion();
//this invokes fade animation
});
How can I add a period of time between these two animations? Thanks!
Full code:
package com.bawp.trivia;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.bawp.trivia.data.Repository;
import com.bawp.trivia.databinding.ActivityMainBinding;
import com.bawp.trivia.model.Question;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
public class MainActivity extends AppCompatActivity {
List<Question> questionList;
Handler mHandler;
private ActivityMainBinding binding;
private int currentQuestionIndex = 0;
SoundPool soundPool;
private int sound1, sound2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
questionList = new Repository().getQuestions(questionArrayList -> {
binding.questionTextview.setText(questionArrayList.get(currentQuestionIndex)
.getAnswer());
updateCounter(questionArrayList);
}
);
mHandler = new Handler();
binding.buttonNext.setOnClickListener(view -> {
currentQuestionIndex = (currentQuestionIndex + 1) % questionList.size();
updateQuestion();
});
binding.buttonTrue.setOnClickListener(view -> {
checkAnswer(true);
updateQuestion();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
changeTheQuestion();
}
}, 3000);
});
binding.buttonFalse.setOnClickListener(view -> {
checkAnswer(true);
updateQuestion();
new Handler().postDelayed(new Runnable() {
public void run() {
changeTheQuestion();
}
}, 3000);
});
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.build();
soundPool = new SoundPool.Builder()
.setMaxStreams(4)
.setAudioAttributes(audioAttributes)
.build();
sound1 = soundPool.load(this, R.raw.correct, 1);
sound2 = soundPool.load(this, R.raw.wrong, 1);
}
private void checkAnswer(boolean userChoseCorrect) {
boolean answer = questionList.get(currentQuestionIndex).isAnswerTrue();
int snackMessageId = 0;
if (userChoseCorrect == answer) {
snackMessageId = R.string.correct_answer;
fadeAnimation();
soundPool.play(sound1, 1, 1, 0, 0, 1);
} else {
snackMessageId = R.string.incorrect;
shakeAnimation();
soundPool.play(sound2, 1, 1, 0, 0, 1);
}
Snackbar.make(binding.cardView, snackMessageId, Snackbar.LENGTH_SHORT)
.show();
}
private void updateCounter(ArrayList<Question> questionArrayList) {
binding.textViewOutOf.setText(String.format(getString(R.string.text_formatted),
currentQuestionIndex, questionArrayList.size()));
}
private void fadeAnimation() {
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
alphaAnimation.setDuration(300);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
binding.cardView.setAnimation(alphaAnimation);
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
binding.questionTextview.setTextColor(Color.GREEN);
}
#Override
public void onAnimationEnd(Animation animation) {
binding.questionTextview.setTextColor(Color.WHITE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private void changeTheQuestion() {
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
alphaAnimation.setDuration(300);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
binding.cardView.setAnimation(alphaAnimation);
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
binding.questionTextview.setTextColor(Color.BLUE);
}
#Override
public void onAnimationEnd(Animation animation) {
currentQuestionIndex = (currentQuestionIndex + 1) % questionList.size();
updateQuestion();
binding.questionTextview.setTextColor(Color.WHITE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private void updateQuestion() {
String question = questionList.get(currentQuestionIndex).getAnswer();
binding.questionTextview.setText(question);
updateCounter((ArrayList<Question>) questionList);
}
private void shakeAnimation() {
Animation shake = AnimationUtils.loadAnimation(MainActivity.this,
R.anim.shake_animation);
binding.cardView.setAnimation(shake);
shake.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
binding.questionTextview.setTextColor(Color.RED);
}
#Override
public void onAnimationEnd(Animation animation) {
binding.questionTextview.setTextColor(Color.WHITE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
Repository.java:
package com.bawp.trivia.data;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.toolbox.JsonArrayRequest;
import com.bawp.trivia.controller.AppController;
import com.bawp.trivia.model.Question;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class Repository {
ArrayList<Question> questionArrayList = new ArrayList<>();
String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<Question> getQuestions( final AnswerListAsyncResponse callBack) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url, null, response -> {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question(response.getJSONArray(i).get(0).toString(),
response.getJSONArray(i).getBoolean(1));
//Add questions to arraylist/list
questionArrayList.add(question);
//Log.d("Hello", "getQuestions: " + questionArrayList);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (null != callBack) callBack.processFinished(questionArrayList);
}, error -> {
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
}
You cannot call Thread.sleep() on the main (UI) thread. This will freeze your app and cause your app to crash with ANR (Application Not Responsive) error.
You can just post a Runnable that will run a chunk of code after a certain period of time. Something like this:
new Handler().postDelayed(new Runnable() {
public void run() {
changeTheQuestion();
}
}, 3000);

Android: Listener for Boolean change

I know that there is a lot of examples, but I can't still make it work.
I need to monitor Boolean value, which change to True, when phone is connected to proper wifi.
Wifi connection and check is done in second thread. Maybe there is problem? I've tried many solutions, and can't get it done.
Wrapper class for variable:
import java.util.ArrayList;
import java.util.List;
public class ConnectivityStatus {
private Boolean status = Boolean.FALSE;
private ConnectivityListener listener;
public Boolean getStatus(){
return status;
}
public void setStatus(Boolean status){
this.status = status;
if(status) {
listener.onChange();
}
}
public void addConnectivityListener(ConnectivityListener l) {
this.listener = l;
}
interface ConnectivityListener{
void onChange();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
...
private ConnectivityStatus mConnectionStatus;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mConnectionStatus = new ConnectivityStatus();
...
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startLoadingScreen();
connectToCamera(mWifiManager);
new Thread(new Runnable() {
public void run() {
long startTime = System.currentTimeMillis();
for(int i = 0; i<=6; i++) {
mConnectionStatus.setStatus(checkWifiSsid(mWifiManager, startTime));
if(mConnectionStatus.getStatus()) {
break;
}
}
}
});
}
});
mConnectionStatus.addConnectivityListener(new ConnectivityStatus.ConnectivityListener() {
#Override
public void onChange(){
openWebView();
}
});
}
I didn't notice earlier but, yes, you're missing something from your threading. You're creating a new thread but you're not telling it to start:
new Thread(new Runnable(){
public void run(){
// Optionally, you can also use log messages for debugging
Log.d("MY_LOG_TAG", "Some message to look for in the log.");
// ...
}
}).start(); // Make sure to tell it to start

How to display a textView Multiple times Based in time

I want to display a TextView during 10 seconds, then make it disappear, every 5 minutes, but I am not able to do it, I have already read this Android CountDownTimer - adding time results in multiple timers running, and many others, but still cant do it, here is what I have tried
private void placeFingerPrint() {
authViewModel.getSession().compose(bindToLifecycle()).subscribe(session -> {
this.session = session;
TextView textView = view.findViewById(R.id.player_finger_print);
MediaItem mediaItem = getPlayingMediaItem();
new CountDownTimer(20000, 10000) {
#Override
public void onTick(long millisUntilFinished) {
if (fingerprint.getChannel() != null && fingerprint.getChannel().contains(mediaItem.getExternalId())) {
textView.setVisibility(View.VISIBLE);
textView.setText(session.getHouseHoldId());
} else {
textView.setVisibility(View.GONE);
}
}
#Override
public void onFinish() {
textView.setVisibility(View.GONE);
start();
}
}.start();
});
We can achieve this using Thread in android. CountDownTimer usually uses if you have a definite end time.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ThreadSample extends AppCompatActivity {
Handler uiHandler = new Handler();
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_sample);
textView = findViewById(R.id.textView);
NameCounter runnable = new NameCounter();
new Thread(runnable).start();
}
class NameCounter implements Runnable {
int count = 0;
boolean show = true;
#Override
public void run() {
while (true) { // add your customized condition here to exit from the loop.
uiHandler.post(new Runnable() {
#Override
public void run() {
if (show)
textView.setVisibility(View.VISIBLE);
else
textView.setVisibility(View.GONE);
}
});
try {
if (show) {
Thread.sleep(10000);
show = false;
} else {
Thread.sleep(5000);
show = true;
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
}
}
}

Loading multiple AdMob videos

For demonstration purposes, the app has one activity that simply offers this:
You click a button, view a rewarded video, and you are rewarded with whatever.
The Problem
How can I load the videos? From what I have seen you can only call mAd.loadAd() once. There are 3 videos, each with their own AD UNIT ID. Each ad unit can have its own listener, but only one video loads so it doesn't matter...
When trying to load multiple videos
For example:
mAd1.loadAd("AD_UNIT_1", new AdRequest.Builder().build());
mAd2.loadAd("AD_UNIT_2", new AdRequest.Builder().build());
mAd3.loadAd("AD_UNIT_3", new AdRequest.Builder().build());
results in only the last video being loaded and this in log:
W/Ads: Loading already in progress, saving this object for future refreshes.
onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd1 = MobileAds.getRewardedVideoAdInstance(this);
mAd2 = MobileAds.getRewardedVideoAdInstance(this);
mAd3 = MobileAds.getRewardedVideoAdInstance(this);
listeners...
mAd1.loadAd() etc
}
Thank you for your help
Edit: It's clear I am thinking about this problem wrong. I have 5+ ad zones that each will play a rewarded video and give a different reward (for example, one gives coins, one gives a level up, and so on..). There is no reason to load 5 videos. I should load one in onCreate(), so it's ready when needed, then load it again after the item is rewarded so it's ready for next time.
So the question remains, if there is just the one video, and thus one ad zone, being loaded onCreate() then how can I track what reward to give?
Here's a simple solution...
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem rewardItem) {
switch(Constants.currentAd) {
case("REWARD1"):
//do something
Constants.currentAd = "";
break;
case("REWARD2"):
//do something
Constants.currentAd = "";
break;
case("REWARD3"):
//do something
Constants.currentAd = "";
break;
}
}
});
mAd.loadAd("REWARDED_VIDEO_UNIT_ID", new AdRequest.Builder().build());
}
public void showRewardedVideo() {
if (mAd.isLoaded()) {
mAd.show();
}
}
Constants.java
public class Constants {
public static String currentAd = "";
}
Showing the ad after button click
rewardButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Constants.currentAd = "REWARD1";
dismiss();
((MainActivity) getActivity()).showRewardedVideo();
}
});
REWARDED_VIDEO_UNIT_ID is one ad unit for rewarded video in AdMob...remove the rest. No need for other units, you can track whatever you like in the listener.
Other simple soluction...
AbstractRewardVideo.java
public abstract class AbstractRewardVideo {
private RewardedVideoAd mAd;
private String adId = "ca-app-pub...";
private Activity activity;
abstract protected RewardedVideoAdListener getListener();
public void init(Activity activity) {
this.activity = activity;
mAd = MobileAds.getRewardedVideoAdInstance(activity);
setAdId(adId);
loadRewardedVideoAd();
}
public Activity getActivity(){
return this.activity;
}
public void loadRewardedVideoAd() {
mAd.loadAd(adId, new AdRequest.Builder().build());
}
public void showVideo(){
setListener(getListener());
if (mAd.isLoaded()) {
mAd.show();
} else {
Utils.exibirToast("Don't loaded!");
}
}
public void setAdId(#NonNull String id){
this.adId = id;
}
public void setListener(RewardedVideoAdListener listener){
mAd.setRewardedVideoAdListener(listener);
}
}
Reward1.java
public class Reward1 extends AbstractRewardVideo {
public Reward1(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
Reward2.java
public class Reward2 extends AbstractRewardVideo {
public Reward2(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity{
Reward1 reward1;
Reward2 reward2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reward1 = new Reward1(this);
reward2 = new Reward1(this);
...
reward1.showVideo();
...
reward2.showVideo();
}
}
MobileAds.initialize ( this, "ca-app-pub-4761500786576152~8215465788" );
RewardedVideoAd mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(Video_Ad.this);
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}

Facebook Feed Dialog with game images and description below

I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}

Categories

Resources