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).
Related
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.
I am trying to populate a spinner using items from a custom class I created via a simple adapter, containing a HashMap. My app keeps crashing when I use setSimpleAdapter(), so I commented it out. But when I use spinner1.setAdapter(dataAdapter), it shows no items on the spinner. Here's my code:
This is in my onCreate():
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <CharSequence> dataAdapter =
new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
//setSimpleAdapter();
// Spinner item selection Listener
addListenerOnSpinnerItemSelection();
// Button click Listener
addListenerOnButton();
// Add spinner data
public void addListenerOnSpinnerItemSelection(){
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("X");
alertDialog.setMessage("" + String.valueOf(spinner1.getSelectedItem()));
alertDialog.setButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Dismisses alert
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
}
Can anyone point me in the right direction? I have been googling for like an hour now. Any help will be appreciated.
Well you didn't post half enough code, but say you have a HashMap<String, Object> then you'd wanna do something like this, passing the array of values into the constructor:
Collection<Object> vals = hashMap.values();
Object[] array = vals.toArray(new Object[vals.size()]);
ArrayAdapter<CharSequence> dataAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, array);
Just replace Object with whatever your custom class is and ensure that you override toString() to define what should be displayed as text.
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);
//
I want to set the position for a spinner. I have a string array for the adapter, i.e,
final String[] cat = { "Highest", "Lowest", "Most Recent"};
But I want my spinner to initially display a blank. So I tried this.
mSpinner.setSelection(-1);
But this doesn't solve my problem. Any ideas how to do this? Help is much needed and appreciated. Thanks.
UPDATE:
My code:
private void displayDialog() {
// TODO displayDialog
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sortBy);
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_layout, null);
promptsView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
final Spinner mSpinner= (Spinner) promptsView
.findViewById(R.id.spDialog);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Sort By...");
builder.setIcon(R.drawable.launcher);
mSpinner.setAdapter(adp);
mSpinner.setSelection(-1);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int pos, long id) {
strSpinner = mSpinner.getSelectedItem().toString();
if(strSpinner.equals("Highest Price")){
highest.setTypeface(Typeface.DEFAULT_BOLD);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortHighestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Lowest Price")){
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT_BOLD);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortLowestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Location")) {
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT_BOLD);
} else {
Log.d("Default", "Default");
}
}
Make your first item Blank.
final String[] cat = {"", "Highest", "Lowest", "Most Recent"};
make your first item blank and set selection of spinner by default is 0.
To set Spinner default value position to -1.
Override the Spinner Class.
that overrides the setAdapter() method.There you can set position to -1.
Please follow the link for details :
How to make an Android Spinner with initial text "Select One"
I have this part of code for spinner. But I get fatal error. What is wrong in here? Thanks! My Activity extends FragmentActivity.
Spinner spinner;
String[] layers = {getString(R.string.a), getString(R.string.b), getString(R.string.c)};
LayoutInflater li = LayoutInflater.from(this);
View v;
v = li.inflate(R.layout.nearest, null);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyActivity.this, android.R.layout.simple_spinner_item, layers);
spinner = (Spinner) findViewById(R.id.spinner_nearest);
spinner.setAdapter(adapter);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(v);
builder.setCancelable(true);
AlertDialog alert = builder.create();
alert.show();}
Is your spinner in nearest.xml?
Then change to
spinner = (Spinner) v.findViewById(R.id.spinner_nearest);