How can I display my Firebase notification message in my textviews in background mode? - firebase-notifications

I want to display my Firebase notification message in textviews in background mode, but it's only working and displaying in foreground mode.
I have already used broadcastReceiver. It is working, but only in the foreground. How can I make it work in background mode?
This is my Firebase Messaging Service class:
public class ProfileActivity extends AppCompatActivity {
TextView notificationTitle, notificationMessage;
public static final String NODE_USERS = "users";
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(mHandler,new IntentFilter("com.example.linguanotification_FCM-MESSAGE"));
setContentView(R.layout.activity_profile);
notificationTitle=findViewById(R.id.title_notification);
notificationMessage=findViewById(R.id.notification_message);
mAuth = FirebaseAuth.getInstance();
FirebaseMessaging.getInstance().subscribeToTopic("updates");
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
saveToken(token);
} else {
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private void saveToken(String token) {
String email = mAuth.getCurrentUser().getEmail();
User user = new User(email, token);
DatabaseReference dbUsers = FirebaseDatabase.getInstance().getReference(NODE_USERS);
dbUsers.child(mAuth.getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Token Saved", Toast.LENGTH_LONG).show();
}
}
});
}
private BroadcastReceiver mHandler = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("title");
String message=intent.getStringExtra("message");
notificationTitle.setText(title);
notificationMessage.setText(message);
}
};
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(), title, body);
}
if (remoteMessage.getData().size()>0)
{
String title = remoteMessage.getData().get("title");
String message= remoteMessage.getData().get("message");
Intent intent = new Intent("com.example.linguanotification_FCM-MESSAGE");
intent.putExtra("title",title);
intent.putExtra("message",message);
LocalBroadcastManager localBroadcastManager=LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context, String title, String body) {
Intent intent = new Intent(context, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.dd)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context);
mNotificationMgr.notify(1, mBuilder.build());
}
}
public class MainActivity extends AppCompatActivity {
//1. Notification Channel
//2. Notification Builder
//3. Notification Manager
public static final String CHANNEL_ID = "12";
public static final String CHANNEL_NAME = "23";
public static final String CHANNEL_DESC = "34";
private EditText editTextEmail, editTextPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.INVISIBLE);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
findViewById(R.id.buttonSignUp).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createUser();
}
});
}
private void createUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextEmail.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email required");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Password should be atleast 6 char long");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
startProfileActivity();
}else{
if(task.getException() instanceof FirebaseAuthUserCollisionException){
userLogin(email, password);
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
private void userLogin(String email, String password){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startProfileActivity();
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
//here we are checking if the user is not null then the user already logged in
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null)
{
startProfileActivity();
}
}
private void startProfileActivity() {
Intent intent = new Intent(this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}

Related

Can't update Item from RecycleView using a Custom Adapter and Listener

I have an updateTask method which opens an alert dialog. I am trying to call this method through a listener in the onBindViewHolder function in my custom adapter.
However my alert dialog does not pop up and while debugging I found out that my update task method is not called.
Please help me understand why.
Thanks
Here is my customAdapter:
public class TasksAdapter extends RecyclerView.Adapter<TasksAdapter.TaskViewHolder> {
private ArrayList<Model> tasks;
private TaskUpdateListener listener;
TasksAdapter(ArrayList<Model> tasks,TaskUpdateListener listener) {
this.tasks = tasks;
this.listener = listener;
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.retrieved_layout, parent, false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TaskViewHolder holder, int position) {
Model task = tasks.get(position);
holder.setDate(task.getDate());
holder.setTask(task.getTask());
holder.setDesc(task.getDescription());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskString = task.getTask();
String descString = task.getDescription();
listener.onTaskUpdate(task, position);
}
});
}
#Override
public int getItemCount() {
return tasks.size();
}
public static class TaskViewHolder extends RecyclerView.ViewHolder {
View mView;
public TaskViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setTask(String task) {
TextView taskTextView = mView.findViewById(R.id.taskTv);
taskTextView.setText(task);
}
public void setDesc(String desc) {
TextView descTextView = mView.findViewById(R.id.descriptionTv);
descTextView.setText(desc);
}
public void setDate(String date) {
TextView dateTextView = mView.findViewById(R.id.dateTv);
}
}
public interface TaskUpdateListener {
void onTaskUpdate(Model model, int position);
}
}
And here is my HomeActivity:
public class HomeActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference userTasksRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String onlineUserID;
private ProgressDialog loader;
private String key = "";
private String task;
private String description;
#Override
public void onBackPressed(){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.homeToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Todo List App");
mAuth = FirebaseAuth.getInstance();
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
loader = new ProgressDialog(this);
mUser = mAuth.getCurrentUser();
onlineUserID = mUser.getUid();
database = FirebaseDatabase.getInstance("https://todolist-bbccd-default-rtdb.europe-west1.firebasedatabase.app");
userTasksRef = database.getReference("users").child(onlineUserID).child("tasks");
floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTask();
}
});
}
private void addTask() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View myView = inflater.inflate(R.layout.input_file, null);
myDialog.setView(myView);
final AlertDialog dialog = myDialog.create();
dialog.setCancelable(false);
final EditText task = myView.findViewById(R.id.task);
final EditText description = myView.findViewById(R.id.description);
Button save = myView.findViewById(R.id.saveBtn);
Button cancel = myView.findViewById(R.id.CancelBtn);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTask = task.getText().toString().trim();
String mDescription = description.getText().toString().trim();
String id = userTasksRef.push().getKey();
String date = DateFormat.getDateInstance().format(new Date());
if (TextUtils.isEmpty(mTask)) {
task.setError("Task Required");
return;
}
if (TextUtils.isEmpty(mDescription)) {
description.setError("Description Required");
return;
} else {
loader.setMessage("Adding your data");
loader.setCanceledOnTouchOutside(false);
loader.show();
Model model = new Model(mTask, mDescription, id, date);
userTasksRef.child(id).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(HomeActivity.this, "Task has been inserted successfully", Toast.LENGTH_SHORT).show();
loader.dismiss();
} else {
String error = task.getException().toString();
Toast.makeText(HomeActivity.this, "Failed: " + error, Toast.LENGTH_SHORT).show();
loader.dismiss();
}
}
});
}
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onStart() {
super.onStart();
ArrayList<Model> tasks = new ArrayList<>();
userTasksRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot taskSnapshot : dataSnapshot.getChildren()) {
Model task = taskSnapshot.getValue(Model.class);
tasks.add(task);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle errors here
}
});
TasksAdapter.TaskUpdateListener listener = new TasksAdapter.TaskUpdateListener() {
#Override
public void onTaskUpdate(Model model, int position) {
updateTask(model, position);
}
};
TasksAdapter adapter = new TasksAdapter(tasks, listener);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void updateTask(Model task, final int position ) {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.update_data, null);
myDialog.setView(view);
final AlertDialog dialog = myDialog.create();
final EditText mTask = view.findViewById(R.id.mEditTextTask);
final EditText mDescription = view.findViewById(R.id.mEditTextDescription);
mTask.setText(task.getTask());
mTask.setSelection(task.getTask().length());
mDescription.setText(task.getDescription());
mDescription.setSelection(task.getDescription().length());
Button delButton = view.findViewById(R.id.btnDelete);
Button updateButton = view.findViewById(R.id.btnUpdate);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasktxt = mTask.getText().toString().trim();
String descriptiontxt = mDescription.getText().toString().trim();
String date = DateFormat.getDateInstance().format(new Date());
Model model = new Model(tasktxt, descriptiontxt, key, date);
userTasksRef.child(key).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(HomeActivity.this, "Data has been updated successfully", Toast.LENGTH_SHORT).show();
}else {
String err = task.getException().toString();
Toast.makeText(HomeActivity.this, "update failed "+err, Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}
});
}
}

viewholder onclickListener null object reference

Attempt to invoke interface method 'void com.example.imovie.adapter.MovieItemClickListener.onMovieClick(com.example.imovie.models.Movie, android.widget.ImageView)' on a null object reference
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MyViewHolder> {
Context context ;
List<Movie> mData;
MovieItemClickListener movieItemClickListener;
public MovieAdapter(Context context, List<Movie> mData, MovieItemClickListener listener) {
this.context = context;
this.mData = mData;
movieItemClickListener = listener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_movie,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.TvTitle.setText(mData.get(i).getTitle());
myViewHolder.ImgMovie.setImageResource(mData.get(i).getThumbnail());
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView TvTitle;
private ImageView ImgMovie;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
TvTitle = itemView.findViewById(R.id.item_movie_title);
ImgMovie = itemView.findViewById(R.id.item_movie_img);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movieItemClickListener.onMovieClick(mData.get(getAdapterPosition()),ImgMovie);//i have a null object reference
}
});
}
}
}
public class HomeFragment extends Fragment implements MovieItemClickListener {
private HomeViewModel homeViewModel;
private List<Slide> listSlides;
private ViewPager slidePager;
private TabLayout indicator;
private RecyclerView moviesRV;
private RecyclerView moviesRV2;
private MovieItemClickListener movieItemClickListener;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
slidePager = root.findViewById(R.id.slider_pager);
indicator = root.findViewById(R.id.indicator);
moviesRV = root.findViewById(R.id.rsViewMovies);
moviesRV2 = root.findViewById(R.id.rsViewMovies2);
iniSlider();
final SliderPagerAdapter sliderPagerAdapteradapter = new SliderPagerAdapter(getContext(), listSlides);
final MovieAdapter movieAdapter = new MovieAdapter(getContext(), DateSource.getPopularMovies(), movieItemClickListener);
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
homeViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
slidePager.setAdapter(sliderPagerAdapteradapter);
indicator.setupWithViewPager(slidePager, true);
moviesRV.setAdapter(movieAdapter);
moviesRV.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
moviesRV2.setAdapter(movieAdapter);
moviesRV2.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
}
});
return root;
}
#Override
public void onMovieClick(Movie movie, ImageView imageView) {
Intent intent = new Intent(getContext(), MovieDetailActivity.class);
intent.putExtra("title", movie.getTitle());
intent.putExtra("imgURL", movie.getThumbnail());
intent.putExtra("imgCover", movie.getCoverPhoto());
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
imageView, "sharedName");
startActivity(intent, options.toBundle());
Toast.makeText(getContext(), "item clicked : " + movie.getTitle(), Toast.LENGTH_LONG).show();
}
class SliderTimer extends TimerTask {
#Override
public void run() {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (slidePager.getCurrentItem() < listSlides.size() - 1) {
slidePager.setCurrentItem(slidePager.getCurrentItem() + 1);
} else {
slidePager.setCurrentItem(0);
}
}
});
}
}
}
private void iniSlider() {
listSlides = new ArrayList<>();
listSlides.add(new Slide(R.drawable.a, "slide title \n movie title"));
listSlides.add(new Slide(R.drawable.b, "slide title"));
listSlides.add(new Slide(R.drawable.a, "slide title \n movie title"));
listSlides.add(new Slide(R.drawable.b, "slide title"));
}
}
If I'm not wrong, HomeFragment.movieItemClickListener is never initialized.
You may want to make the following changes in HomeFragment:
1. Delete the line
private MovieItemClickListener movieItemClickListener;
2. In this line
final MovieAdapter movieAdapter = new MovieAdapter(getContext(), DateSource.getPopularMovies(), movieItemClickListener);
change movieItemClickListener to this, because HomeFragment implements MovieItemClickListener.
That should fix the NullPointerException.

Firebase App / Not loading questions

Hey i made a firebase quiz app but the questions stored in the database don't load in the app. can someone tell me what is wrong ?
This is the code to load questions :
public class Start extends AppCompatActivity {
Button btnLigue1, btnChampionsligue;
FirebaseDatabase database;
DatabaseReference questions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
database = FirebaseDatabase.getInstance();
questions = database.getReference("Questions");
loadQuestion();
btnChampionsligue = (Button)findViewById(R.id.btnChampionsligue);
btnLigue1 = (Button)findViewById(R.id.btnLigue1);
btnChampionsligue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(Start.this,Playing2.class);
startActivity(intent1);
finish();
}
});
btnLigue1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Start.this,Playing.class);
startActivity(intent);
finish();
}
});
}
private void loadQuestion() {
// Fist, clear List if have old question
if (Common.questionList.size() > 0)
Common.questionList.clear();
questions.orderByChild("Questions").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapchot : dataSnapshot.getChildren())
{
Question ques = postSnapchot.getValue(Question.class);
Common.questionList.add(ques);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Random list
Collections.shuffle(Common.questionList);
}
}
And this is the code when i am playing :
public class Playing extends AppCompatActivity implements View.OnClickListener{
private DatabaseReference mDatabase;
final static long INTERVAL = 1000;
final static long TIMEOUT = 7000;
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,score=0,thisQuestion=0,totalQuestion,correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB,btnC,btnD;
TextView txtScore,txtQuestionNum,question_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
mDatabase = FirebaseDatabase.getInstance().getReference("Questions");
//Views
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestionNum = (TextView)findViewById(R.id.txtTotalQuestion);
question_text = (TextView)findViewById(R.id.question_text);
question_image = (ImageView)findViewById(R.id.question_image);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
btnA = (Button)findViewById(R.id.btnAnswerA);
btnB = (Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion) // Il reste des questions dans la liste
{
Button clickedButton =(Button)view;
if(clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
{
score+=10;
correctAnswer++;
showQuestion(++index); // Question suivante
}
else if (clickedButton.getText()!=(Common.questionList.get(index).getCorrectAnswer()))
{
showQuestion(++index);
}
else
{
// Si mauvaise question TODOO proposer de regarder une pub pour passer à la question suivante
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
//startActivity(intent);
finish();
}
txtScore.setText(String.format("%d",score));
}
}
private void showQuestion(int index) {
if (index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d / %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
// Si il y a une image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
// Si c'est une question texte : masquer l'image
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
btnC.setText(Common.questionList.get(index).getAnswerC());
btnD.setText(Common.questionList.get(index).getAnswerD());
mCountDown.start(); // Start timer
}
else
{
// Si c'est la dernière question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
// startActivity(intent);
// finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}

What happens if user clicks on deep link in the app itself

If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.

Sending a tweet from Blackberry -- working in simulator, but not working on device

I am working on Blackberry Twitter integration to tweet a message on twitter.
The app is working fine in simulator but giving exception when I am running it on a device.
Here is the exception I am getting every time I run the app on the device{
OAuth_IO_Exception
I have done some research and saw a solution to set the correct date time on device, but it still is not working.
Here is my code:
import com.kc.twitter.activity.TweetToFriend;
import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class TwitterScreen extends MainScreen {
private final String CONSUMER_KEY = "{redected}";
private final String CONSUMER_SECRET = "{redected}";
private final String CALLBACK_URL = "http://kingdomconnectng.net/redirect.php";
private LabelField _labelStutus;
public static OAuthDialogWrapper pageWrapper = null;
private ShowAuthBrowser showAuthBrowserScreen;
private String adminMessage;
public String adminMessages[];
boolean done=false;
Credential c ;
TweetToFriend tw;
public static StoreToken _tokenValue;
public static boolean isTweetPosted=false;
public static boolean isTweeterScreen =false ;
public TwitterScreen(final String adminMessage)
{
this.adminMessage=adminMessage;
isTweeterScreen = true ;
showAuthBrowserScreen = new ShowAuthBrowser();
_tokenValue = StoreToken.fetch();
/*if(_tokenValue.token.equalsIgnoreCase("nothing"))
{*/
showAuthBrowserScreen.doAuth(null);
UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
/*}
else
{
final Token t = new Token(_tokenValue.token, _tokenValue.secret,
_tokenValue.userId, _tokenValue.username);
Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, t);
TweetToFriend tw=new TweetToFriend();
boolean done=tw.doTweet(adminMessage, c);
if(done==true){
Dialog.alert("Tweet posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
else{
Dialog.alert("Tweet not posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
}*/
}
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
//if(isTweetPosted==false){
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
_labelStutus = new LabelField("KingdomConnect App" );
//add(_labelStutus );
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
}
else
{
this.deleteAll();
add(b);
pageWrapper.login(pin);
}
}
catch ( Exception e )
{
final String message = "Error loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
System.out.println("Access denied! -> " + response );
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
final Token myToken = token;
_tokenValue = StoreToken.fetch();
_tokenValue.token = myToken.getToken();
_tokenValue.secret = myToken.getSecret();
_tokenValue.userId = myToken.getUserId();
_tokenValue.username = myToken.getUsername();
_tokenValue.save();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
try{
deleteAll();
c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, myToken);
tw = new TweetToFriend();
/*done=tw.doTweet("KingdomConnect App: "+adminMessage, c);
if(done == true)
{
Dialog.alert( "Buzz posted successfully." );
close();
}
*/
prepareMessage(adminMessage);
}catch(NullPointerException e){
}catch(Exception e){
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
//TWEET METHOD
public void tweet(String message){
done=tw.doTweet("KingdomConnect: "+message, c);
/*if(done == true){
Dialog.alert( "Shared successfully." );
close();
} */
}
//PREPARE MESSAGE TO TWEET
public void prepareMessage(String msg){
int charLimit = 120;
int _msgSize = msg.length();
int i=0;
int parts = _msgSize/124;
try {
if(_msgSize > charLimit){
int temp1=0,temp2=charLimit;
while(i<parts+1){
String data = null;
if(i==parts){
data = msg.substring(temp1, _msgSize);
}else{
data = msg.substring(temp1, temp2);
temp1=temp2;
temp2=temp2+charLimit;
}
i++;
tweet(data);
}
Dialog.alert( "Shared successfully." );
}else{
tweet(msg);
//System.out.println("Data:======================"+msg);
}
}catch (Exception e) {
System.out.println("e = "+e);
}
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}

Resources