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()
Related
I have implemented a list View with CheckedTextView . When I am selecting a particular row and clicking on checkbox then checkbox becomes invisible. Also sometimes any other row get selected.I want to select multiple items.
please help...
List_row Layout is..
<CheckedTextView
android:id="#+id/service_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20sp"
android:layout_marginBottom="10dp"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:textColor="#000000"
android:checked= "false"
>
CustomListView is:
import java.util.ArrayList;
public class CustomListView extends ArrayAdapter {
//to reference the Activity
private final Activity context;
String value;
//to store the list items
private final String[] nameArray;
CheckedTextView nameTextField;
public CustomListView(Activity context, ArrayList nameArra) {
super(context, R.layout.row_list_view, nameArrayParam);
this.context = context;
this.nameArray = nameArrayParam;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.row_list_view, null, true);
//this code gets references to objects in the listview_row.xml file
nameTextField = (CheckedTextView)
rowView.findViewById(R.id.service_name);
//this code sets the values of the objects to values from the arrays
nameTextField.setText(nameArray[position]);
// perform on Click Event Listener on CheckedTextView
nameTextField.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("customList",";clicked row is " +
nameTextField.getText().toString());
if (nameTextField.isChecked()) {
// set check mark drawable and set checked property to false
value = "un-Checked";
nameTextField.setCheckMarkDrawable(R.color.colorAccent);
nameTextField.setChecked(false);
}
else {
// set check mark drawable and set checked property to true
value = "Checked";
nameTextField.setChecked(true);
}
Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
}
});
return rowView;
}
In my MainActivity.java, I have used listView setOnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
selected_Item = (String) arg0.getItemAtPosition(arg2);
Toast.makeText(AskForService.this, "Clicked item is" + selected_Item, Toast.LENGTH_LONG).show();
}
});
After implementing these code I can see -
ListView with checked TextView
ListView Can Scroll showing all the list items
on clicking a particular row..listview click listener is called and showing the Toast but checkbox becomes white(invisible) and sometimes another row get selected...Please help
Create a model class which contains a flag "isChecked" and set the data according to the model inside adapter
This link might be helpful : https://stackoverflow.com/a/40285759/8770539
Use an arraylist to store checked item's position.
call notifyDataSetChanged() for onclick()
Use this,
if(list.contains(position)) {
nameTextField.setChecked(true);
}
else {
nameTextField.setChecked(false);
}
nameTextField.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(list.contains(position))
{
list.remove(position);
}
else
{
list.add(position);
}
notifyDataSetChanged();
}
});
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();
}
});
I have a OnItemSelectedListener for my Spinner, but it is not called when the selected item is the same as the previous one.I also implemented OnClickListener but it doesn't worked. I have found some solution. But I don't know how can I use it. I need to catch every-time a user click on an item.
JAVA CODE:
spn_filter_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),String.valueOf(position),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
XML CODE:
<Spinner
android:id="#+id/spn_filter_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
If you select an different item onItemSelected gets called.
If you don't select a different one it means you have not selected an item, then onNothingSelected gets called.
spn_filter_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),String.valueOf(position),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
CharSequence message = "called when the selected item is the same as the previous one";
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
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();**
}
}