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);
}
}
Related
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();
}
});
}
}
My question maybe simple simple but I don't understand why Vaadin combobox tries to get a colletion of nested entities set in a combobox if I do not call these items of collection.
See this:
#Entity
public class Estado extends AbstractEntity {
private String nome;
private String sigla;
#OneToMany(mappedBy = "estado")
private List<Municipio> municipios;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public List<Municipio> getMunicipios() {
return municipios;
}
public void setMunicipios(List<Municipio> municipios) {
this.municipios = municipios;
}
private void initCbEstados() {
if (cbEstados.isEmpty()) {
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
}
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void updateViewToEdit(){
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
***//this throws LazyInitializationException***
cbEstados.setValue(estado);
updateCbMunicipios();
}
I do not call at any time estado.getMunicipios. But apparently the behavior of the combobox tries to infer in the municipios released the exception.
Is this expected behavior?
I don't think it should be?
Sory, fisrt post on stack overflow and i was not familiar with the platform and ended not posting the entire code. The error occurred in
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
that during the debug was not visible because it was occurring within the vaadin classes. The problem was solved by searching for the municpios in updateCbMunicpios(); So when FormBase calls beforeEnter(BeforeEnterEvent event) the readBean() set values on cbEstados that fires ValuechangeListener and load the LazeInicializaTionExceptions because Entity comes from the Request Scoope and not Fully filed to set the Value of Municipio in cbMunicipios. And cbMunicipios would be empty firing anhoter error from Vaadin.
public class FornecedorForm extends CadastroFormBaseGenerics<Fornecedor, FornecedorService> {
private static final long serialVersionUID = -5599427454458715210L;
EstadoService estadoService;
#PropertyId("ativo")
private Checkbox ckAtivo;
#PropertyId("razaoSocial")
private TextField txtRazaoSocial;
#PropertyId("nomeFantasia")
private TextField txtNomeFantasia;
#PropertyId("cnpj")
private TextField txtCnpj;
#PropertyId("contato")
private TextField txtContato;
#PropertyId("telefoneContato")
private TextField txtTelContato;
#PropertyId("telefone")
private TextField txtTelefone;
#PropertyId("observacao")
TextArea txtObservacao;
private ComboBox<Estado> cbEstados;
private ComboBox<Municipio> cbMunicipios;
private TextField txtCep;
private TextField txtLogradouro;
private TextField txtNumero;
private TextField txtComplemento;
#PropertyId("emailContato")
EmailField txtEmailContato;
private FormLayout layout;
HorizontalLayout layoutEstado;
public FornecedorForm(#Autowired EstadoService estadoService) {
super(Fornecedor.class, "Fornecedor");
this.estadoService = estadoService;
updateViewToEdit();
}
protected void configureAdditionalBinds() {
getBinder().bind(cbEstados, "endereco.estado");
getBinder().bind(cbMunicipios, "endereco.municipio");
getBinder().bind(txtCep, "endereco.cep");
getBinder().bind(txtLogradouro, "endereco.logradouro");
getBinder().bind(txtNumero, "endereco.numero");
getBinder().bind(txtComplemento, "endereco.complemento");
}
private void initCbEstados() {
cbEstados = new ComboBox<Estado>("Estado");
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void initCbMunicpios() {
cbMunicipios = new ComboBox<Municipio>("Município");
cbMunicipios.setItemLabelGenerator(Municipio::getNome);
cbMunicipios.setWidth("50%");
cbMunicipios.setReadOnly(true);
}
private void updateCbMunicipios() {
if (cbEstados.getValue() != null) {
cbMunicipios.clear();
cbMunicipios.setReadOnly(false);
Estado estado = estadoService.findMunicipios(cbEstados.getValue());
cbMunicipios.setItems(estado.getMunicipios());
} else {
cbMunicipios.clear();
cbMunicipios.setReadOnly(true);
}
}
#Override
protected void initViewComponents() {
layoutEstado = new HorizontalLayout();
layout = new FormLayout();
layoutEstado.setSizeFull();
initCbEstados();
initCbMunicpios();
ckAtivo = new Checkbox("Ativo ?", true);
txtRazaoSocial = new TextField("Razão Social");
txtNomeFantasia = new TextField("Nome Fantasia");
txtCnpj = new TextField("CNPJ");
txtCnpj.setWidth("25%");
// txtCnpj.setErrorMessage("CNPJ Incorreto.");
// txtCnpj.setPattern("^[0-9]{2}?[-s.]?[0-9]{3}[-s.]?[0-9]{3}[-s/]?[0-9]{4}[-s-]?[0-9]{2}$");
txtTelefone = new TextField("Telefone");
txtContato = new TextField("Nome Contato");
txtTelContato = new TextField("Telefone Contato");
txtEmailContato = new EmailField("Email Contato");
txtEmailContato.setClearButtonVisible(true);
txtEmailContato.setErrorMessage("Formato do E-mail incorreto");
txtEmailContato.setRequiredIndicatorVisible(false);
txtLogradouro = new TextField("Logradouro");
txtNumero = new TextField("Número");
txtNumero.setWidth("50px");
txtCep = new TextField("CEP");
txtCep.setPattern("^[0-9]{5}?[-s-]?[0-9]{3}$");
txtCep.setPlaceholder("00000-000");
txtCep.setRequired(true);
txtCep.setErrorMessage("Informe o CEP");
txtCep.setWidth("75px");
txtComplemento = new TextField("Complemento");
txtObservacao = new TextArea("Observações");
layout.add(ckAtivo, 2);
layout.add(txtCnpj, 2);
layout.add(txtRazaoSocial, txtNomeFantasia);
layout.add(layoutEstado, 2);
layout.add(txtLogradouro, txtNumero);
layout.add(txtComplemento, txtCep, txtTelefone);
HorizontalLayout layoutContato = new HorizontalLayout(txtContato, txtTelContato, txtEmailContato);
layoutContato.setSizeFull();
txtContato.setWidth("40%");
txtEmailContato.setWidth("40%");
txtTelContato.setWidth("20%");
layout.add(layoutContato, 2);
layout.add(txtObservacao, 2);
super.formLayout.add(layout);
layoutEstado.add(cbEstados, cbMunicipios);
configureAdditionalBinds();
}
protected void updateViewToEdit() {
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
estado = estadoService.findMunicipios(estado);
cbEstados.setValue(estado);
}
}
#Override
protected void getNewEntityToPersist() {
entity = new Fornecedor();
entity.setEndereco(new Endereco());
ckAtivo.setValue(true);
}
}
public abstract class CadastroFormBaseGenerics<T, SERVICE extends ServiceInterface<T>> extends FormLayout
implements BeforeEnterObserver {
private static final long serialVersionUID = 7069232922824142288L;
protected T entity;
#Autowired
private SERVICE service;
private final Class<T> beanClass;
private Binder<T> binder;
private String nomeDoBean;
protected boolean isEditMode;
private Button btnSave = new Button("Salvar");
private Button btnDelete = new Button("Excluir");
private Button btnCancel = new Button("Cancelar");
protected VerticalLayout formLayout = new VerticalLayout();;
private HorizontalLayout buttonsLayout = new HorizontalLayout();
public CadastroFormBaseGenerics(Class<T> beanClass, String nomeDoBean) {
this.beanClass = beanClass;
this.nomeDoBean = nomeDoBean;
}
protected abstract void initViewComponents();
#PostConstruct
private void inicialize() {
checkEditMode();
initBinder();
initViewComponents();
addComponentAsFirst(formLayout);
configureFormLayout();
getEntityToEdit();
updateViewToEdit();
}
protected abstract void updateViewToEdit();
protected void initBinder() {
binder = new BeanValidationBinder<T>(beanClass);
}
protected void setPlaceHolders(String beanName) {
String primeiraLetra = "" + beanName.charAt(0);
primeiraLetra = primeiraLetra.toUpperCase();
char letraMaiuscula = primeiraLetra.charAt(0);
char[] cArray = beanName.toCharArray();
cArray[0] = letraMaiuscula;
beanName = new String(cArray);
for (int i = 0; i < formLayout.getComponentCount(); i++) {
Component c = formLayout.getComponentAt(i);
if (c.getClass().getName().equals("com.vaadin.flow.component.textfield.TextField")) {
TextField aux = (TextField) c;
aux.setPlaceholder(aux.getLabel() + " " + beanName + "...");
aux.setClearButtonVisible(true);
}
}
}
protected void configureFormLayout() {
formLayout.setSizeFull();
// formLayout.setMargin(true);
formLayout.setSpacing(true);
formLayout.setPadding(true);
formLayout.setAlignItems(Alignment.AUTO);
formLayout.setMargin(true);
// add(formLayout, 2);
configureButtonsLayout();
}
void configureButtonsLayout() {
btnDelete.setVisible(false);
btnSave.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnDelete.addThemeVariants(ButtonVariant.LUMO_ERROR);
buttonsLayout = new HorizontalLayout();
buttonsLayout.add(btnSave, btnDelete, btnCancel);
buttonsLayout.setMargin(true);
buttonsLayout.setPadding(true);
buttonsLayout.setSizeFull();
configureButtonEvents();
add(buttonsLayout, 2);
}
private void configureButtonEvents() {
btnSave.addClickListener(saveEvent -> save());
btnDelete.addClickListener(deleteEvent -> delete());
btnCancel.addClickListener(cancelEvent -> clearForm());
}
private void save() {
String msg = nomeDoBean + " Alterada(o) com sucesso.";
if (!isEditMode) {
msg = nomeDoBean + " Cadastrada(o) com sucesso.";
getNewEntityToPersist();
// getNewEntity();
}
try {
getBinder().writeBean(entity);
service.save(entity);
clearForm();
showSucess(msg);
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " já cadastrado. Verique.");
logException(e, "Metodo save()");
} catch (ValidationException e) {
showWarnig("Verique os campos obrigatórios.");
}
}
/**
* {#summary} Você deve implementar o {#code} entity = New POJO este método é
* chamado toda vez que {#code} save() para criar um novo BEAN a ser persistido.
*/
protected abstract void getNewEntityToPersist();
private void delete() {
try {
service.delete(entity);
clearForm();
showSucess(nomeDoBean + " removida(o) com sucesso.");
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " não pode ser removida(o), pois existem registros que dependem dele. %/n "
+ "Inative-o para que não seja mais exibido.");
}
}
#SuppressWarnings("unchecked")
private void getEntityToEdit() throws ClassCastException {
if (isEditMode) {
btnDelete.setVisible(true);
this.entity = (T) VaadinServletRequest.getCurrent().getAttribute("entityToEdit");
}
}
private boolean checkEditMode() {
if (VaadinServletRequest.getCurrent().getAttribute("entityToEdit") != null) {
isEditMode = true;
} else {
isEditMode = false;
}
return isEditMode;
}
/**
* Sempre deve ser chamado após um click no botão salvar, cancelar ou excluir
*/
protected void clearForm() {
// Desabilita o botão para excluir um Bean Cadastrado
btnDelete.setVisible(false);
// Seta editmode para falso, garantido que a proxima interação
// seja com um bean novo
isEditMode = false;
clearBinder();
}
protected void clearBinder() {
binder.readBean(null);
}
protected void showSucess(String message) {
createNotification(message, NotificationVariant.LUMO_SUCCESS, 3000);
}
protected void showError(String message) {
createNotification(message, NotificationVariant.LUMO_ERROR, 5000);
}
protected void showWarnig(String message) {
createNotification(message, NotificationVariant.LUMO_CONTRAST, 10000);
}
private void createNotification(String message, NotificationVariant variant, int duration) {
Notification n = new Notification(message);
n.setDuration(7000);
n.addThemeVariants(variant);
n.setPosition(Position.TOP_CENTER);
n.open();
}
protected void logException(Exception e, String logDesc) {
System.out.println("################ " + logDesc.toUpperCase() + " $$ " + getClass().getSimpleName()
+ " ################");
e.printStackTrace();
}
public Binder<T> getBinder() {
return binder;
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
binder.bindInstanceFields(this);
if (entity != null) {
getBinder().readBean(entity);
}
}
}
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.
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);
}
}
Good afternoon.
I'm starting programming in java and blackberry.
I am developing an application with three windows, which I will show basic information about the device, these windows are already done and working.
I need to create a process running in the background, this process will run every 10 minutes.
As I make this process run in the background and is working to close the windows?
This is the kind that runs the application:
public class InfoBerry extends UiApplication{
public vtnprincipal vtnprincipal;
public vtnbateria vtnbateria;
public vtnestado vtnestado ;
public vtnacerca vtnacerca;
public InfoBerry(){
}
public static void main(String[] args) {
InfoBerry theApp = new InfoBerry();
theApp.mostrarpantalla();
}
public void mostrarpantalla(){
vtnprincipal = new vtnprincipal(this);
vtnbateria = new vtnbateria(this);
vtnestado = new vtnestado(this);
vtnacerca = new vtnacerca(this);
// Inicailizamos los componentes de la pantalla principal
vtnprincipal.incventana();
// La pnemos en lo alto de la pila de pantallas
pushScreen(this.vtnprincipal);
}
}
And this is the class you need to run in the background.
As I have to make the call to this class to run in the background?
class iconnoti extends MainScreen{
//icono de la temperatura
EncodedImage imgtem =
EncodedImage.getEncodedImageResource("icon_bateria_t.png");
ApplicationIcon icontem = new ApplicationIcon(imgtem);
//icono de la carga de la bateria
EncodedImage imgcarga =
EncodedImage.getEncodedImageResource("icon_bateria.png");
ApplicationIcon iconcarga = new ApplicationIcon(imgcarga);
//icono de la memoria
EncodedImage imgmemo =
EncodedImage.getEncodedImageResource("icon_memoria.png");
ApplicationIcon iconmemo = new ApplicationIcon(imgmemo);
ApplicationIcon mIcon = icontem;
boolean act;
public iconnoti() {
}
public void rotar_temperatura(){
cron c1;
actualizar_icono(icontem);
actualizar_valor(DeviceInfo.getBatteryTemperature());
c1 = new cron(2,10000);
c1.start();
}
public void rotar_memoria(){
cron c1;
actualizar_icono(iconmemo);
actualizar_valor(34);
c1 = new cron(3,10000);
c1.start();
}
public void rotar_nivel(){
cron c1;
actualizar_icono(iconcarga);
actualizar_valor(DeviceInfo.getBatteryLevel());
c1 = new cron(1,10000);
c1.start();
}
public void iniciar_servicio() {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator Indicator =
reg.register(mIcon, false, true);
} catch (Exception e) {
}
}
public void parar_servicio() {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
reg.unregister();
} catch (Exception e) {
}
}
void actualizar_valor(int value) {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator =
reg.getApplicationIndicator();
appIndicator.setValue(value);
} catch (Exception e) {
}
}
void actualizar_icono(ApplicationIcon icon) {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator =
reg.getApplicationIndicator();
appIndicator.setIcon(icon);
} catch (Exception e) {
}
}
}
class cron extends Thread {
//private ApplicationIcon icono;
public int valor;
private int tiempo;
iconnoti icon = new iconnoti();
public cron(int v, int t){
valor = v;
tiempo = t;
}
public void run() {
try {
sleep(tiempo);
} catch (InterruptedException e) {
}
if(valor == 1){
icon.rotar_temperatura();
}else if(valor == 2){
icon.rotar_memoria();
}else if(valor == 3){
icon.rotar_nivel();
}
}
}
Thanks for the help.
Background Application is a kind of process, so there is no GUI at least on the beginning.
You should extend Application instead of UIApplication class
You should not push screen there, just move everything from iconnoti class to cron class and run it in Application constructor:
public class BerryInfoApp extends Application {
public BerryInfoApp() {
UpdateThread updateThread = new UpdateThread(10*60*1000);
updateThread.run();
}
public static void main(String[] args) {
(new BerryInfoApp()).enterEventDispatcher();
}
}
class UpdateThread extends Thread {
EncodedImage imgtem = EncodedImage
.getEncodedImageResource("icon_bateria_t.png");
ApplicationIcon icontem = new ApplicationIcon(imgtem);
EncodedImage imgcarga = EncodedImage
.getEncodedImageResource("icon_bateria.png");
ApplicationIcon iconcarga = new ApplicationIcon(imgcarga);
EncodedImage imgmemo = EncodedImage
.getEncodedImageResource("icon_memoria.png");
ApplicationIcon iconmemo = new ApplicationIcon(imgmemo);
ApplicationIcon mIcon = icontem;
static final int ACTION_NONE = 0;
static final int ACTION_BATTERY_TEMP = 1;
static final int ACTION_MEMORY = 2;
static final int ACTION_BATTERY_LEVEL = 3;
int mAction = ACTION_BATTERY_LEVEL;
long mPeriod;
public UpdateThread(int period) {
mPeriod = period;
}
public void stop() {
mAction = ACTION_NONE;
}
public void run() {
iniciar_servicio();
while (mAction != ACTION_NONE) {
switch (mAction) {
case ACTION_BATTERY_TEMP:
rotar_temperatura();
mAction = ACTION_MEMORY;
break;
case ACTION_MEMORY:
rotar_memoria();
mAction = ACTION_BATTERY_LEVEL;
break;
case ACTION_BATTERY_LEVEL:
rotar_nivel();
mAction = ACTION_BATTERY_TEMP;
break;
default:
break;
}
try {
sleep(mPeriod);
} catch (InterruptedException e) {
}
}
parar_servicio();
}
public void rotar_temperatura() {
actualizar_icono(icontem);
actualizar_valor(DeviceInfo.getBatteryTemperature());
}
public void rotar_memoria() {
actualizar_icono(iconmemo);
actualizar_valor(34);
}
public void rotar_nivel() {
actualizar_icono(iconcarga);
actualizar_valor(DeviceInfo.getBatteryLevel());
}
public void iniciar_servicio() {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator Indicator = reg.register(mIcon, false, true);
} catch (Exception e) {
}
}
public void parar_servicio() {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
} catch (Exception e) {
}
}
void actualizar_valor(int value) {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
appIndicator.setValue(value);
} catch (Exception e) {
}
}
void actualizar_icono(ApplicationIcon icon) {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
appIndicator.setIcon(icon);
} catch (Exception e) {
}
}
}