The first factor to note in this situation is that to call the method setOnItemSelectedListener()
requires the implementation of the interfaceAdapterView.onItemSelectedListener
in the class. An example:
public class JSONOAsyncTask
extends AsyncTask<String, Void, Boolean>
implements AdapterView.OnItemSelectedListener{
...
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Another factor is that one should explore more the AsyncTask
. This class provides some Features interesting: onPreExecute()
and onPostExecute()
. These methods serve to define some action we wish to perform before the asynchronous task and what we wish to do after the task is completed.
Let’s go to the this
First you should know, like any programming language, that there are some reserved words. In JAVA, it has the this and the super, respectively the instructions this()
and super()
.
Keywords are divided into categories according to their purpose. Some words are used in more than one scenario. The meaning of the word depends on the context in which it is used. This is called: semantic load. Java, for having few key words and purposely reuse the words whenever possible has a much larger semantic load than other languages. However, in practice it is not possible to confuse the various meanings.
The reserved word super is used to reference methods or attributes of the super class. Imagine that you have a class called Manager that inherits from the Employee class and that both classes have a method called calcularPontos()
. Being in the Manager class how to call the method calcularPontos()
of the superclass (Funcio)?
//o compilador sabe que você quer utilizar o método da superclasse e não o método local.
super.calcularPontos();
Reserved word this is normally used within methods that receive parameters with the same class instance attribute name or to do reference to the object itself, let’s take an example:
public void setNome(String nome){
/*o this nesse caso informar que o atributo de instancia
"nome" vai receber o valor do paramentro "nome".
Se não tivesse o this, como ele saberia? ficaria ambiguo.*/
this.nome = nome;
}
Another example, imagine you’re in class Gerente
and calls the method of another class that expects as argument an object of the class Gerente
. Then you can use the this
to do this.
/* o método salvar gerente espera como argumento um objeto da classe
Gerente, como estou dentro da classe gerente eu disse que o
objeto a ser salvo é "este"(this).*/
Armazenamento.salvarGerente(this);
this: used to indicate the intended scope for invoking
a method or access to an attribute is own object chain.
Also used to reference another constructor of the same
class. It is also used as a way of referring to the instance that encapsulates
the current instance when in a nested class
A comparison
super: used to indicate the intended scope for invoking
a method or access to an attribute is that of the parent class. Also used
to reference another constructor of the class immediately
superior in the hierarchy of inheritance
Situation
Here’s how you could solve this case. First, by implementing AdapterView.OnItemSelectedListener
to the superclass JSONAsyncTask
. Soon after declaring the Spinner
as a global variable. No onPreExecute
is made the connection between XML and JAVA, which would be before running the doInBackGround
. In background the list of categories is created, as an example, and also the definition of the adapter. Finally, in the onPostExecute
, is attached the data to the adapter. Below follows exactly as it should be AsyncTask
personalized:
public class JSONOAsyncTask extends AsyncTask<String, Void, Boolean> implements AdapterView.OnItemSelectedListener{
private Spinner spinner;
private ArrayAdapter<String> dataAdapter;
@Override
protected void onPreExecute() {
super.onPreExecute();
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
@Override
protected Boolean doInBackground(String... urls) {
// criando lista de elementos
List<String> categories = new ArrayList<String>();
categories.add("Balaco Bacco");
categories.add("Capitão G. Nascimento");
categories.add("JBuenos's Dias");
categories.add("Marceleza");
categories.add("Ramarelo");
// criação do adapter
dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return false;
}
protected void onPostExecute(Boolean result) {
// anexando o adapter aos dados
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Recently I asked a question that is What difference between methods to obtain a context?, where I comment that we can beyond the this
, obtain the context in various ways, with different methods, such as getApplicationContext()
and the getBaseContext()
which apparently has the same purpose. Read the answers and see more details about how to use.
Reference
this
refers to the instance of the class itself. When you say it doesn’t work, what exactly do you mean? You can improve the issue to make it clearer?– Pagotti
Maybe it’ll help Reserved word "this". Is there an error/Exception? or is it an unexpected result? Android Studio provides some hint (on the line as a problem)?
– rray
it is not clear what is your doubt... what is the error?
– ldeoliveira
I edited the question, I hope it was clear... call this off on create, it’s not working........
– Camila Yamamoto
@ldeoliveira, answering your question, when I use the second example, ie a function outside the "onCreate", the android does not let continue.. just like that! he underlines all that red line!
– Camila Yamamoto