AutoCompleteTextView in a AlertDialog Builder - android

I have tried to work this out but nothing pops into my head, the following code is a part of an application that has movies and if i click a search button it creates a dialog builder with a AutoCompleteTextView for typing a name of a movie.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(ThisScreen.search_context, android.R.style.Theme_Black));
///// autocomplete thingie
String[] name_mov = new String[movie_categ.size()];
name_mov = movie_categ.toArray(name_mov);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, name_mov);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View search_View = inflater.inflate(R.layout.this_movie_search, null);
myAutoComplete = (AutoCompleteTextView)
search_View.findViewById(R.id.movie_name);
myAutoComplete.setAdapter(adapter);
myAutoComplete.setThreshold(2);
/////
alertDialogBuilder.setView(searchView);
alertDialogBuilder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
isFirstDialog = 0;
}
});
alertDialog = alertDialogBuilder.create();
if (movie_categ.isEmpty() )
{
Toast.makeText(ThisScreen.search_context, "Verify net conn.", Toast.LENGTH_LONG).show();
isFirstDialog = 0;
}
else alertDialog.show();
and this_movie_search.xml has
<AutoCompleteTextView
android:id="#+id/movie_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/button_search"
android:textColorHint="#android:color/white"
android:hint="#string/search_hint"
android:ems="10"
android:maxLength="50"
/>
The list with the suggestions doesnt appear, any ideas why?

I searched for the answer for too long and didn't saw the obvious, i should have declared my myAutoComplete from the beginning as 'AutoCompleteTextView' type, and it works.
final AutoCompleteTextView myAutoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.AutoCompleteTextView_declared_in_the_xml);
// autocomplete thingie
String[] name_mov = new String[movie_categ.size()];
name_mov = movie_categ.toArray(name_mov);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, name_mov);
myAutoComplete.setAdapter(adapter);
myAutoComplete.setThreshold(2);
//

Related

I want spinner to automatically be opened when the page gets loaded android

I want the spinner drop down to get opened automatically when the page gets loaded.
what can i do for that?
<Spinner
android:entries="#array/cities_arrays"
android:id="#+id/spinner"
android:layout_width="230sp"
android:gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:spinnerMode="dropdown"
tools:layout_editor_absoluteY="16dp"
android:background="#drawable/spinner_styling"
android:layout_marginLeft="80sp"
android:layout_marginRight="80sp"
android:layout_marginTop="10sp"
android:layout_below="#+id/app_bar"/>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
placesList = new ArrayList<>();
cities = getResources().getStringArray(R.array.cities_arrays);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
listView = (ListView) findViewById(R.id.listView);
// This is to avoid automatic keypad opening as soon as the page loads.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
placesList.clear();
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteText);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
listAdapter = new ListViewAdapter(this, R.layout.row,placesList);
spinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
spinner.performClick();
mButton = (Button) findViewById(R.id.plus_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(mContext);
View dialogView = li.inflate(R.layout.custom_dialog, null);
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(mContext);
// set title
alertDialogBuilder.setTitle("Add Location");
// set custom dialog icon
//alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// set custom_dialog.xml to alertdialog builder
alertDialogBuilder.setView(dialogView);
final EditText userInput = (EditText) dialogView
.findViewById(R.id.autoCompleteTextView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//etOutput.setText(userInput.getText());
dialog.cancel();
}
})
.setNegativeButton("Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
city = cities[index];
if(index != 0) {
PLACES_OF_INTEREST_URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + city + "+point+of+interest&language=en&key=" + API_KEY + "";
listView.clearAnimation();
listAdapter.clear();
new GetPlaces().execute();
listAdapter.addAll(placesList);
listView = (ListView) findViewById(R.id.listView);
listView.invalidateViews();
listAdapter.notifyDataSetChanged();
listView.setAdapter(listAdapter);
System.out.println(city);
Toast.makeText(getApplicationContext(), "Selected: " + city, Toast.LENGTH_LONG).show();
}
index = -1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplicationContext(),"Please Select a City!", Toast.LENGTH_LONG).show();
}
});
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.application.microsoft.wayfarer, PID: 24758
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.application.microsoft.wayfarer/com.application.microsoft.wayfarer.activities.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
You can achieve this like below :-
Spinner yourSpinner = (Spinner) findViewById(R.id.yourSpinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yourSpinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
yourSpinner.performClick();
and in your method comment this below line
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Add dropdownlist spinner to alert dialogue Android Studio

I'm trying to add a search form with a edittext and dropdownlist spinner to alert dialogue. I have managed to get the edit text to display, but I cannot figure out how to add the spinner. I'm new to android so any help would be appreciated.
private void LoadSearchDialogue()
{
android.app.AlertDialog.Builder alertDialogSearchForm = new android.app.AlertDialog.Builder(this);
alertDialogSearchForm.setTitle("Search Form");
alertDialogSearchForm.setMessage("Please complete form");
final EditText textViewInputUsername = new EditText(this);
final Spinner spinnerSearchOptions = new Spinner(this);
Spinner dropdownSearchOptions = (Spinner)findViewById(R.id.spinnerSearchOptions);
String[] items = new String[]{"Customer", "Employee","Date" };
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdownSearchOptions.setAdapter(adapter);
mQuery = (EditText) findViewById(R.id.query);
mSearchOption = (Spinner) findViewById(R.id.spinnerSearchOptions);
alertDialogSearchForm.setView(textViewInputUsername);
alertDialogSearchForm.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here, overriding alert dialogue button
}
});
final android.app.AlertDialog dialog = alertDialogSearchForm.create();
dialog.show();
dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Boolean closeAlertDialogueOnValidInput = false;
//Check if query is entered,
String mQueryString = textViewInputUsername.getText().toString().trim();
if(mQueryString.length()<=0)
{
Toast.makeText(SearchActivity.this, "Please enter query", Toast.LENGTH_SHORT).show();
}
else
{
String q = mQueryString.toString();
String o = mSearchOption.getSelectedItem().toString();
SearchResults(q, o);
}
if(closeAlertDialogueOnValidInput)
dialog.dismiss();
}
});
}
Use the below code
public class WvActivity extends Activity {
TextView tx;
String[] s = { "India ", "Arica", "India ", "Arica", "India ", "Arica",
"India ", "Arica", "India ", "Arica" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayAdapter<String> adp = new ArrayAdapter<String>(WvActivity.this,
android.R.layout.simple_spinner_item, s);
tx= (TextView)findViewById(R.id.txt1);
final Spinner sp = new Spinner(WvActivity.this);
sp.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
sp.setAdapter(adp);
AlertDialog.Builder builder = new AlertDialog.Builder(WvActivity.this);
builder.setView(sp);
builder.create().show();
}
}
I suggest that you create a simple xml layout for your dialog:
<!-- alert.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/mySpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
After that you inflate a View from this layout file, set this view in setView method, fill the Spinner with data and do all the stuff that you need to do. All the things that you currently do to define behavior for button clicks will remain the same; but the listeners for your EditText and Spinner, if needed, will be set outside the Dialog (with findViewById and setOnClickListener).
To inflate a View from xml you need to get LayoutInflater and use it to create a View:
View alertView = getLayoutInflater().inflate(R.layout.alert, null);
To populate the Spinner with data, you should use an Adapter. There is some code from here:
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);
If you would like to stick to your way of creation of the View, you need to add not only your EditText to your AlertDialog, but a ViewGroup (LinearLayout for example), that will contain both EditText and Spinner.

Refresh listview/display newly added data to listview android

I'm new to Android Sqlite DB Dev't so I need your help guys. I was able to do the basic CRUD operations. Now I want to know how to refresh the listview to display the newly added data. I've looked into adapter.notifyDataSetChanged but I wonder why it's not working for me. Here's what I've tried so far
private void initControls() {
SearchAuto = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
String[] SearchItems = getResources().getStringArray(R.array.DogSearch);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.searchitems,SearchItems);
SearchAuto.setAdapter(adapter);
SearchAuto.setThreshold(0);
search = (Button) findViewById (R.id.handle);
search.setOnClickListener(this);
lv = (ListView) findViewById (R.id.lv);
values = dbHelper.getAllAnimals(ANIMALTYPE);
for (int i = 0; i < values.length; i++) {
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
}
// TODO onItemClick
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String strDog = parent.getItemAtPosition(position).toString();
Intent i = new Intent(DogClass.this, Dogs.class);
i.putExtra("dog_name", strDog);
startActivity(i);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.addanimal, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// get prompt_addprayer.xml view
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.prompt_addanimal, null);
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText etBreed = (EditText) promptsView
.findViewById(R.id.etBreed);
final EditText etDescription = (EditText) promptsView
.findViewById(R.id.etDescription);
final EditText etDiet = (EditText) promptsView
.findViewById(R.id.etDiet);
final EditText etShelter = (EditText) promptsView
.findViewById(R.id.etShelter);
final EditText etHygiene = (EditText) promptsView
.findViewById(R.id.etHygiene);
final EditText etMedication = (EditText) promptsView
.findViewById(R.id.etMedication);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
String strAnimalType = ANIMALTYPE;
String strBreed = etBreed.getText().toString();
String strDesc = etDescription.getText().toString();
String strDiet = etDiet.getText().toString();
String strShelter = etShelter.getText().toString();
String strHygiene = etHygiene.getText().toString();
String strMedication = etMedication.getText().toString();
dbHelper.addAnimalInfo(strAnimalType, strDesc,
strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
lvAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
}
Any ideas? I really need to get this working. Thanks
dbHelper.addAnimalInfo(strAnimalType, strDesc, strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
lvAdapter.notifyDataSetChanged();
This is where you lacked. What you did is, you just inserted data into database, still you are remaining to bring data from database and bind it with adapter, and after that you may call notifyDataSetChanged();, and you'll achieve what you want...
Try this:
dbHelper.addAnimalInfo(strAnimalType, strDesc, strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
values = dbHelper.getAllAnimals(ANIMALTYPE);
lvAdapter.clear();
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lvAdapter.notifyDataSetChanged();
Note: you should not write this way. Your code:
for (int i = 0; i < values.length; i++) {
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
}
If your getAllAnimals() method is returning an arrayList then you simply need to:
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
The last argument of your ArrayAdapter constructor needs List<Item> to be passed. And then just call setAdapter(adapter) of ListView.
For more clarification, refer this SO link: notifyDataSetChanged example
http://androidadapternotifiydatasetchanged.blogspot.in

Null Pointer Exception when using a spinner in alertDialog

This is the code I wrote:
// create a view in dialog box
final View fileView = getLayoutInflater().inflate(R.layout.filename, null);
String[] array_spinner = new String[5];
array_spinner[0]="1";
array_spinner[1]="2";
array_spinner[2]="3";
array_spinner[3]="4";
array_spinner[4]="5";
Spinner s = (Spinner) findViewById(R.id.sp_CAT);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
s.setSelection(2);
//Spinner mCAT = (Spinner) findViewById(R.id.sp_CAT);
//ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
//fileView.getContext(), R.array.a_CAT, android.R.layout.simple_spinner_item);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//mCAT.setAdapter(adapter);
EditText mSID = (EditText) fileView.findViewById(R.id.et_SID);
EditText mSCD = (EditText) fileView.findViewById(R.id.et_SCD);
EditText mNUM = (EditText) fileView.findViewById(R.id.et_NUM);
final String tSID=mSID.getText().toString();
final String tSCD=mSCD.getText().toString();
final String tNUM=mNUM.getText().toString();
// show dialog box
new AlertDialog.Builder(CameraActivity3.this).setTitle("Set FileName")
.setView(fileView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(CameraActivity3.this, tSID+tSCD+tNUM, Toast.LENGTH_SHORT).show();
}// public void onClick
}) // setPositiveButton
.setNegativeButton("Cancel", null).show();
However, I am receiving a null pointer exception. After some testing (commenting out some lines), it seems to be related to the spinner adapter. Did I get something wrong?
Use this:
Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);
write below code line
Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);
instead of
Spinner s = (Spinner) findViewById(R.id.sp_CAT);
For anyone looking at this in the future using DialogFragment to build the AlertDialog, you can't use just this in the ArrayAdapter. My solution is below:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View myView = inflater.inflate(R.layout.program_num_spinner_popup, null);
builder.setView(myView);
programNumbers = (Spinner) myView.findViewById(R.id.prog_num_spinner_list);
ArrayAdapter<CharSequence> numbersAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.program_numbers, android.R.layout.simple_spinner_item);
numbersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
programNumbers.setAdapter(numbersAdapter);
I replaced this with this.getActivity() combined with Zaz Gmy's answer and Dipak Keshariya's answer (which are the same).

Create ListView programmatically

Hi I am new in Android. Could anyone tell me pls whats the wrong with the following code:
public class ListApp extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lText = new TextView(this);
lText.setId(0);
ListView lView = new ListView(this);
String[] lStr = new String[]{"AA","BB", "CC"};
ArrayAdapter lAdap = new ArrayAdapter(this,lText.getId(),lStr);
lView.setAdapter(lAdap);
lView.setFocusableInTouchMode(true);
setContentView(lView);
}
}
here's a solution that does not require you to write any xml layouts. it uses standard android layouts where possible and no inflation is necessary:
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
dialog = builder.create();
Try this..
Paste the following code in list_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
Here is the activity class....
public class UsersListActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Best practice is to separate view (xml layout) and controller (Activity).
If you dont want this, try to put
setContentView(lView);
at the beginning of onCreate
public class ListApp extends ListActivity
Make a layout XML file with your listview and use findViewById to set it's adapter after first setting the content view to your layout

Categories

Resources