my issue is that whenever I add a lecture to the array list in the next activity, it calls back to this activity and updates it. However, for some reason onItemSelected is called right away as soon as I get back to the calling activity and I'm sent to the Lecture activity (the displayLectureIntent is started right away) as soon as I get back to the calling activity without even actually selecting anything from the spinner.
Could it be that as soon as I add something to the spinner, the spinner chooses the first object as default and therefore it "selects" it? Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_manager0);
Intent receivedIntent = getIntent();
if (receivedIntent.hasExtra("lectureManagerExtra")) {
lectureManager = (LectureManager) getIntent().getSerializableExtra("lectureManagerExtra");
update();
} else {
lectureManager = new LectureManager();
}
}
public void update() {
Spinner spinner = (Spinner) findViewById(R.id.lecturespinner);
ArrayAdapter<String> lectureadapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item, lectureManager.getLectureNames());
lectureadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(lectureadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
startActivity(displayLectureIntent);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
}
please add "select" string on lectureManager.getLectureNames() array at the top
so that the array's size is increased by 1
And setSelectedIndex to 0 .
and
modify onItemSelected method as followings
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HEYYY", Toast.LENGTH_LONG).show();
Intent displayLectureIntent = new Intent(getBaseContext(), LectureActivity.class);
displayLectureIntent.putExtra("lectureExtra",
lectureManager.returnLecture(adapterView.getItemAtPosition(position).toString()));
**if(position !=0){
startActivity(displayLectureIntent);
}
else{
Toast.makeText(getApplicationContext(), " select the lecture.", Toast.LENGTH_LONG).show();**
}
}
Related
Hi in the below code I have a edit button .If I am click on edit button setting the spinner values to the spinner .
click on edit button spinner value is setting the adapter.
String speclizations = getArguments().getString("speclization_name");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, Specializationnames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSpecialization.setAdapter(dataAdapter1);
if(spinnerSpecialization.getSelectedItem().equals(0)){
speclizations = getArguments().getString("speclizations");
Log.d("salutation_names",salutation_names);
}else {
speclizations=spinnerSpecialization.getSelectedItem().toString();
}
Same value I am passing after click on save button I am passing the spinner value without selecting want to pass the same value.but it is throwing an error.
spinner.getslecteditem().toString();//null
Can any one help me how to resolve the issue.
Try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if(spinner.getslecteditem().equals(0))
{
//Display a toast message to select any values from the Spinner
}
else {
str = spinner.getslecteditem().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
I need to get getItemIdAtPosition() from listView to get the id of the records from sqlite database. When i click on the listView on any item, it always shows "null" not showing the id.
this is the code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int id= ((int) listView.getItemIdAtPosition(i));
//create our intent, as per usual
Intent intent=new Intent(Tutorial10.this, Activity2.class);
intent.putExtra(ID_EXTRA, id);
startActivity(intent);
}
});
This activity2.java
public class Activity2 extends Activity{
String passedVar=null;
private TextView passedView=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
//Get our passed variable from our intent's EXTRAS
passedVar=getIntent().getStringExtra(Tutorial10.ID_EXTRA);
//find out text view
passedView=(TextView)findViewById(R.id.passed);
//display our passed variable!!!
passedView.setText("YOU CLICKED ON="+passedVar);
}
}
You should change this line
int id= ((int) listView.getItemIdAtPosition(i));
with this
long id = adapterView.getItemIdAtPosition(i);
I hope this fixes your problem.
According to the Android official document here, there's no definition about the purpose of this function. It seems to call to getItemId() in Adapter, and getItemId() returns the value of Id in SQLite.
I guess you need to use SimpleCursorAdapter to work with the SQLite.
I have one screen with two spinners. The choices in the second spinner depend on the user choice in the first spinner.
Here is my code:
For the first spinner:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.oman_states));
final MaterialBetterSpinner materialDesignSpinner = (MaterialBetterSpinner)
findViewById(R.id.states_list); // states spinner
materialDesignSpinner.setAdapter(arrayAdapter);
for the second spinner:
final MaterialBetterSpinner materialDesignSpinner2 = (MaterialBetterSpinner)
findViewById(R.id.hospitals_list);
and I implemented the following listener in the second spinner:
materialDesignSpinner2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (materialDesignSpinner.getText().toString() == getString(R.string.muscat)) {
ArrayAdapter<String> muscatHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.muscat_hospitals));
materialDesignSpinner2.setAdapter(muscatHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.albatna)) {
ArrayAdapter<String> albatnaHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.albatan_hospitals));
materialDesignSpinner2.setAdapter(albatnaHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.musandam)) {
ArrayAdapter<String> smaelHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.musandam_hospitals));
materialDesignSpinner2.setAdapter(smaelHospitals);
} else if (gm.spinnerChecking(materialDesignSpinner)) {
Toast.makeText(v.getContext(), getString(R.string.choose_state_first), Toast.LENGTH_LONG).show();
}
System.out.println("Working");
}
});
when I press on the spinner, the application crashes
showing the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Filter.filter(java.lang.CharSequence,
android.widget.Filter$FilterListener)' on a null object reference
at
android.widget.AutoCompleteTextView.performFiltering(AutoCompleteTextView.java:971)
at
com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner.onFocusChanged(MaterialBetterSpinner.java:49)
how can I make the second spinner choices based on the first spinner?
UPDATE:
after applying #dominicoder solution, the onItemSelected is not executed for some reason because System.out.println() doesn't print "work" to the console.
Here is the code for the onItemSelected :
materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
System.out.println("works");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
A couple of things:
Do NOT do string comparisons using == in Java. Use String.equals()
Use the position of the selection of the first spinner to determine what to show, not the text that happens to be showing in that position.
You should update the state of the second spinner in response to the changing of the state of the first spinner, not checking the first spinner state when it's time to show something in the second spinner
You should create just one adapter for your second spinner that you update as needed, instead of creating a new instance each time.
With these suggestions in mind, I would recommend something more like this:
// Second adapter is a class field
private ArrayAdapter<String> secondSpinnerAdapter;
// Initialize it ONCE in onCreate with no items to begin with
secondSpinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line);
materialDesignSpinner2.setAdapter(secondSpinnerAdapter);
// When something is selected in the first adapter,
// update the options in the second adapter
materialDesignSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private String[] getStringsForPosition(int position) {
switch(position) {
case 0: return getResources().getStringArray(R.array.musandam_hospitals);
// Add other cases
}
}
This eliminates string equality checks, removes duplication, and makes the intent "when something in the first spinner is a selected, update the options in the second spinner" much clearer.
Hope that helps!
you shouldn't set an on click listener. instead of that do this
materialDesignSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I would like to call an action every time my spinner selects a new item. The current setup is that an action is called when a button is pressed.
My approach:
Create a new function: public void onSpinnerItemSelection(View V){...}
Then in content_home.xml I would add onSpinnerItemSelection to onClick for Spinner.
This isn't working. I'm not familiar with Android errors and I'm struggling to interpret these errors.
Unfortunately, myApp has stopped
Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
Step by step:
1ªDeclare variables from the layoutSpinner sp; the arraylist in this case ArrayList listTeams; and the adapter Adapter adapter;
2ªinstances
private void instances() {
sp = (Spinner) findViewById(R.id.spinner);
listaTeam = new ArrayList();
3º add items for the adapter
private void listAdapter() {
listaTeam.add(new Equipo(R.string.Atleti));
adaptador = new Adaptador(MainActivity.this, listaEquipo);
sp.setAdapter(adapter);
now we make actions, use onItemSelected.
public void onItemSelected(AdapterView parent, View view, int position, long id) {
Toast.makeText("this is my team", Toast.LENGTH_LONG).show();
}
https://www.youtube.com/watch?v=H3W0-Nv664I
Here is an example:
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText("log", "position = " position, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText("log", "onNothingSelected", Toast.LENGTH_LONG).show();
}
});
in an android website, I found an article about how to create a text entry widget that provides auto-complete suggestions. (Following is the link to the site; and it shows all the codes).
http://developer.android.com/resources/tutorials/views/hello-autocomplete.html
Can anyone please tell me how I can capture the input entered by the user? For example, if the user chooses “Canada”, is there a way I can know the result in the “HelloAutoComplete.java” activity? Any help would be greatly appreciated.
public class HelloAutoComplete extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
String[] countries = getResources().getStringArray(R.array.countries_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);
textView.setAdapter(adapter);
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("Canada")) {
Toast.makeText(getApplicationContext(), "Result Canada", Toast.LENGTH_SHORT).show();
} //Does not get an out put when I select Canada.
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} }
textView.getText();
textView.getText().toString(); // If you need an actual String
Currently your code does not hook up the listener to the text view.
You need to either (a) use an immediate listener:
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("Canada")) {
Toast.makeText(getApplicationContext(), "Result Canada", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Or (b) if you want to use the activity as the listener (I wouldn't) have it implement the interface and set the itemSelectedListener to this. But yuck.
To set the selected text into another text element, a few changes must be made. First, the layout must now include the autocomplete "component", and the additional text view. We set the "parent" layout to vertical orientation, create a new horizontal layout for the autoselect stuff, and add a new text view.
<LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
a:orientation="vertical"
a:layout_width="fill_parent"
a:layout_height="wrap_content"
a:padding="5dp">
<LinearLayout a:orientation="horizontal"
a:layout_width="fill_parent"
a:layout_height="wrap_content">
<TextView a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:text="Country"/>
<AutoCompleteTextView a:id="#+id/autocomplete_country"
a:layout_width="fill_parent"
a:layout_height="wrap_content"
a:layout_marginLeft="5dp"/>
</LinearLayout>
<TextView a:id="#+id/selected_country"
a:layout_height="wrap_content"
a:layout_width="fill_parent"/>
</LinearLayout>
The activity gets a new TextView instance property, which I'm calling selectedCountry. I'm not showing its declaration. The onCreate method looks it up by ID, and the select listener just updates it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Text view for selected country.
selectedCountry = (TextView) findViewById(R.id.selected_country);
textView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedCountry.setText(adapterView.getItemAtPosition(i).toString());
}
public void onNothingSelected(AdapterView<?> adapterView) { }
});
}
The best way would be to set an "item selected listener" which will notify you when the user has picked something from the available entries. See the docs. With this you can get the item from the adapter that they picked (and, conversely, whatever you defined for that item's text).
Example:
textView.setOnItemSelectedListener( new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View selectedView,
int selectedPosition, long selectedId) {
//do stuff here
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
Try this:
textView.getText().toString();
Then display it through Toast.
Use :
textView.getText().toString()