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);
}
}
}
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();
}
});
}
}
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);
}
}
I am trying to implement authentication and authorization using Spring Security Framework, but I am having a hard time, Im stuck in this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clienteBO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected br.com.logtec.dao.GenericCrudDAO br.com.logtec.business.GenericCrudBO.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'crudDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected javax.persistence.EntityManager br.com.logtec.dao.GenericCrudDAO.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.persistence.EntityManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject(), #br.com.logtec.factory.DataFactory()}
Those are my related classes:
#Named("clienteBO")
public class ClienteBO extends PersonificacaoBO<Cliente>{
private static final long serialVersionUID = 119528316663693560L;
public ClienteBO() {
super();
}
#Override
public Feedback salvar(Cliente instancia) {
instancia.getPessoa().setCliente(true);
//TODO PEGAR EMPRESA DO USUARIO LOGADO
// if(instancia.getEmpresa() == null)
// throw new RuntimeException("O cliente deve obrigatoriamente possuir uma empresa");
return super.salvar(instancia);
}
#Override
public Feedback salvar(Cliente instancia, CrudDAO<Cliente> dao) {
instancia.getPessoa().setCliente(true);
return super.salvar(instancia, dao);
}
#Override
protected Exemplo criarExemplo(Cliente pesquisa) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return super.criarExemplo(pesquisa);
}
#Override
public Feedback salvar(Collection<Cliente> instancias) {
for (Cliente cliente : instancias) {
cliente.getPessoa().setCliente(true);
}
return super.salvar(instancias);
}
#Override
public Feedback salvar(Collection<Cliente> instancias, CrudDAO<Cliente> dao) {
for (Cliente cliente : instancias) {
cliente.getPessoa().setCliente(true);
}
return super.salvar(instancias, dao);
}
}
public abstract class PersonificacaoBO<T extends Personificacao> extends GenericCrudBO<T>{
private static final long serialVersionUID = 5475960092794378740L;
#Override
protected Exemplo criarExemplo(T pesquisa) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Exemplo exemplo = super.criarExemplo(pesquisa);
exemplo.excludeField("pessoa.cliente");
exemplo.excludeField("pessoa.funcionario");
exemplo.excludeField("pessoa.fornecedor");
exemplo.excludeField("pessoa.usuario");
exemplo.excludeField("pessoa.contador");
return exemplo;
}
}
#Named("crudBO")
public class GenericCrudBO<E extends EntidadeBase> implements CrudBO<E>{
private static final long serialVersionUID = 1L;
private static final String DEFAULT_ERROR_MESSAGE = "Um erro inesperado ocorreu, contate o administrador do sistema.";
private static final String DEFAULT_SUCESS_MESSAGE = "Operação realizada com sucesso!";
#Inject
#Named("crudDAO")
protected GenericCrudDAO<E> dao;
public GenericCrudBO() {
super();
}
public GenericCrudBO(GenericCrudDAO<E> dao) {
super();
this.dao = dao;
}
public Feedback salvar(E instancia, CrudDAO<E> dao) {
Feedback feedback;
try {
dao.atualizar(instancia);
feedback = new Feedback(TipoFeedback.SUCESSO, EtapaFeedback.CADASTRO, DEFAULT_SUCESS_MESSAGE);
} catch (RuntimeException e) {
feedback = new Feedback(TipoFeedback.ERRO, EtapaFeedback.CADASTRO, DEFAULT_ERROR_MESSAGE);
throw e;
}
return feedback;
}
public Feedback salvar(Collection<E> instancias, CrudDAO<E> dao) {
try {
dao.cadastrar(instancias);
return new Feedback(TipoFeedback.SUCESSO, EtapaFeedback.CADASTRO, "Operação realizada com sucesso");
} catch (Exception e) {
return new Feedback(TipoFeedback.ERRO, EtapaFeedback.CADASTRO, "Erro ao salvar, contate o administrador");
}
}
#Override
public Feedback salvar(Collection<E> instancias) {
return salvar(instancias, dao);
}
public Feedback salvar(E instancia) {
return salvar(instancia, dao);
}
#Override
public Feedback deletar(E entidade) {
Feedback feedback;
try {
dao.deletar(entidade);
feedback = new Feedback(TipoFeedback.SUCESSO, EtapaFeedback.CADASTRO, DEFAULT_SUCESS_MESSAGE);
} catch (RuntimeException e) {
feedback = new Feedback(TipoFeedback.ERRO, EtapaFeedback.DELECAO, DEFAULT_ERROR_MESSAGE);
}
return feedback;
}
public E pesquisarPorId(Class<E> clazz, Long id) {
return dao.pesquisarPorId(clazz, id);
}
public E pesquisarPorId(E instancia) {
return dao.pesquisarPorId(instancia);
}
public List<E> pesquisar(Class<E> clazz) {
return dao.pesquisarTodos(clazz);
}
/**
* Pesquisa para entidades simples sem composição
*/
#Override
public List<E> pesquisar(E pesquisa) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Exemplo exemplo = criarExemplo(pesquisa);
return dao.pesquisar(exemplo);
}
protected Exemplo criarExemplo(E pesquisa) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Exemplo exemplo = new Exemplo(pesquisa);
exemplo.excludeField("serialVersionUID");
exemplo.setMatchingMode(MatchingMode.ANYWHERE);
exemplo.excludeZeroes();
return exemplo;
}
#Override
public int total(E pesquisa) {
return this.dao.total(pesquisa);
}
public List<E> listarLazy(E pesquisa, int startingAt, int maxPerPage, String sortField, String sortOrder) {
inicializarCamposPesquisa(pesquisa);
return this.dao.listarLazy(pesquisa, startingAt, maxPerPage, sortField, sortOrder);
}
protected void inicializarCamposPesquisa(E pesquisa) {
//método que deverá ser implementado pelas classes filhas que quiserem filtrar os resultados no lazyList
}
public String getListIds(List<EntidadeBase> entidades) {
StringBuilder builder = new StringBuilder('(');
EntidadeBase e = null;
for (int i = 0; i < entidades.size(); i++) {
e = entidades.get(i);
builder.append(e.getId());
if(i < entidades.size()-1) {
builder.append(',');
}
}
builder.append(')');
return builder.toString();
}
#SuppressWarnings("unchecked")
protected Class<E> getClassType() {
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
return (Class<E>) parameterizedType.getActualTypeArguments()[0];
}
}
#Named("crudDAO")
public class GenericCrudDAO<E extends EntidadeBase> implements CrudDAO<E>{
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CrudDAO.class);
#Inject
#DataFactory
protected EntityManager entityManager;
public GenericCrudDAO() {
super();
}
public GenericCrudDAO(EntityManager entityManager) {
super();
this.entityManager = entityManager;
}
#Override
public void cadastrar(E instancia) {
entityManager.getTransaction().begin();
entityManager.persist(instancia);
entityManager.getTransaction().commit();
}
public void cadastrar(Collection<E> instancias) {
try {
entityManager.getTransaction().begin();
for(E e : instancias) {
entityManager.merge(e);
}
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
throw e;
}
}
#Override
public void atualizar(E instancia) {
entityManager.getTransaction().begin();
entityManager.merge(instancia);
entityManager.getTransaction().commit();
}
#Override
public void deletar(E instancia) {
entityManager.getTransaction().begin();
entityManager.remove(entityManager.merge(instancia));
entityManager.getTransaction().commit();
}
public E pesquisarPorId(Class<E> clazz, Long id) {
return (E) entityManager.find(clazz, id);
}
#SuppressWarnings("unchecked")
public E pesquisarPorId(E instancia) {
Class<E> clazz = (Class<E>) instancia.getClass();
return (E) entityManager.find(clazz, instancia.getId());
}
#SuppressWarnings("unchecked")
public List<E> pesquisarTodos(Class<E> clazz) {
List<E> lista = new ArrayList<E>();
lista = entityManager.createQuery(" FROM " + clazz.getName()).getResultList();
return lista;
}
#Override
public List<E> pesquisar(Exemplo exemplo) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return QBE.using(entityManager).getList(exemplo);
}
#Override
public E pesquisarUnico(Exemplo exemplo) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return QBE.using(entityManager).getSingle(exemplo);
}
#Override
#SuppressWarnings("unchecked")
public List<E> pesquisar(String queryString) {
return entityManager.createQuery(queryString).getResultList();
}
#SuppressWarnings("unchecked")
#Override
public List<E> pesquisar(String queryString, Map<String, Object> param) {
String key = null;
Query query = entityManager.createQuery(queryString);
for(Map.Entry<String, Object> entry : param.entrySet()) {
key = entry.getKey().trim();
key = key.startsWith(":") ? key.substring(1) : key;
query.setParameter(key, entry.getValue());
}
return query.getResultList();
}
public int total(E pesquisa) {
Long count = 0L;
try {;
Query q = entityManager.createQuery("SELECT count(*) FROM "
+ pesquisa.getClass().getName());
count = (Long) q.getSingleResult();
} catch (Exception e) {
LOGGER.error("Erro ao buscar total listagem lazy", e);
}
return count.intValue();
}
public void rollback() {
entityManager.getTransaction().rollback();
}
#SuppressWarnings("unchecked")
protected Class<E> getClassType() {
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
return (Class<E>) parameterizedType.getActualTypeArguments()[0];
}
#SuppressWarnings("unchecked")
public List<E> listarLazy(E pesquisa, int startingAt, int maxPerPage,
String sortField, String sortOrder) {
List<E> lista = new ArrayList<E>();
try {
Query q = entityManager.createQuery("FROM "
+ pesquisa.getClass().getName());
q.setFirstResult(startingAt);
q.setMaxResults(maxPerPage);
lista = q.getResultList();
} catch (Exception e) {
LOGGER.error("Erro ao buscar listagem Lazy", e);
}
return lista;
}
}
I'm a begginer on Spring Security, being so, any help is welcome, thanks
If I get this right, you want to use Spring Security for security and CDI for dependency injection.
In that case, you need to make sure that Spring and CDI don't try to manage the same beans. Even when you don't use Spring Core directly, you now have both Spring and CDI on your classpath. When Spring discovers javax.inject.Inject on its classpath, it will treat #Inject as synonymous to #Autowired and try to inject Spring beans into the annotated injection target.
That's why you get the exception - it's Spring and not CDI complaining about a missing bean.
Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.
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) {
}
}
}