Android - spinner within dialog won't populate - android

I'm trying to add a two spinners inside a dialog (popup). The problem I'm having is populating the spinners. I get no error I can see, and basically the same code works if It's in a tab-fragment, and not the dialog.
This is the code that does not popluate the spinners inside the dialog.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
League league;
league = ((LeagueMainActivity)getActivity()).getLeague();
View v = inflater.inflate(R.layout.diaglog_add_match, null);
Spinner spinner1 = (Spinner) v.findViewById(R.id.spinner_dialog_player1);
Spinner spinner2 = (Spinner) v.findViewById(R.id.spinner_dialog_player2);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
.setTitle("Add match")
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//LoginDialogFragment.this.getDialog().cancel();
/* do I really need to do anything??? */
}
});
AlertDialog dialog = builder.create();
return dialog;
}
This is the code that works within a (tabbed) fragment:
public class UnnamedFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_unnamed, container, false);
Spinner spinner1 = (Spinner) rootView.findViewById(R.id.spinner);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
return rootView;
}
}

Okay so what I did wrong was inflating/creating two independent views with the same context.
First I did:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
And then:
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
So I set the view for the builder as a new view, and not the same ones I used for the spinner.
So instead if I do:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
builder.setView(v)
That does the trick.

Related

How to close a dialog after the user selects an item from a spinner?

I have a dialog with a spinner. Currently, the dialog and the spinners works fine. However, the spinner doesn't close after I selected an item. I need it to be close and return to the activity after an item is selected. Thanks.
Here's the code for my dialog.
String[] s = {"A", "B", "C", "D", "E", "F" };
final ArrayAdapter<String> adp = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, s);
final Spinner sp = new Spinner(getActivity());
//sp.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
sp.setAdapter(adp);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
Log.d("selectedItem:", selectedItem);
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(sp);
builder.create().show();
There is no method on Spinner to close it,when spinner item is selected, and that will close your spinner, add to your setOnItemSelectedListener
sp.setSelection(int position)
and then just change your AlertDialog constructor a bit, put alert.dismiss(); to dismiss the AlertDialog after user selects an item in your spinner
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(sp);
final AlertDialog alert = builder.create();
alert.show();
Try this
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final Spinner sp = new Spinner(getActivity());
sp.setAdapter(adp);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
Log.d("selectedItem:", selectedItem);
builder.dismiss();
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
}
});
builder.setView(sp);
builder.create().show();

Spinner is not populated in a fragment

I am trying to add 2 spinner in a fragment.These spinners are interconnected.When user select a value,2nd spinner will be populated with value.
Example:1st spinner have 2 values as "Car" & "Bus".
When users select "car",2nd spinner will be populated by color of the car as "Red","Blue".Again,if user select Bus,2nd spinner will be populated by color of bus as "Green","White".
I have made this in mainactivity successfully.But when I try to implement in a fragment ,2nd spinner is not populated and also there is no error showing.
I am providing the code that I have tried to implement in fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_info_form, container, false);
//spCountries = (Spinner) v.findViewById(R.id.idCrimePlace);
//set the spinners
crimePlace = (Spinner) rootView.findViewById(R.id.idCrimePlace);
metro = (Spinner) rootView.findViewById(R.id.idMetro);
crimePlace.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
crimePlace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spCrimePlace= String.valueOf(crimePlace.getSelectedItem());
//Toast.makeText(this, crimePlace, Toast.LENGTH_SHORT).show();
if(spCrimePlace.contentEquals("Car")) {
List<String> list = new ArrayList<String>();
list.add("Red");
list.add("Blue");
list.add("Others");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
metro.setAdapter(dataAdapter);
}
if(spCrimePlace.contentEquals("Bus")) {
List<String> list = new ArrayList<String>();
list.add("Green");
list.add("White");
list.add("Other");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
metro.setAdapter(dataAdapter2);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
Try calling your adapter like:
ArrayAdapter dataAdapter = new ArrayAdapter(this.getActivity(),
android.R.layout.simple_spinner_item, list);
And also use equals() instead of contentEquals

Updating list fragment with list adapter

Currently ran into an issue trying to update a list fragment with a dialogfragment input (or dummy input) everything compiles but don't see any change to the list.
Please let me know what you think. Thanks.
public class NewEventDialogFragment extends DialogFragment {
private List<GlobalClass> mItems;
EditText editText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//editText = (EditText) findViewById(R.id.editText);
builder.setMessage("What Would You Like to Name the Event?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mItems = new ArrayList<GlobalClass>();
mItems.add(new GlobalClass("Whoiszzzzzzzzzzzzzzthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfzzzzzzzzzzzzzsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthzzzzzzzzzzzzzzsdfdsfis", "Addosdfsdfmg"));
// Create the adapter to convert the array to views
MainTabsPagerAdapter adapter = new MainTabsPagerAdapter(getActivity(), mItems);
// Attach the adapter to a ListView
adapter.addAll(mItems);
adapter.notifyDataSetChanged();
//setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
builder.setView(view);
return builder.create();
}
}
private List<GlobalClass> mItems; // ListView items list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the items list
mItems = new ArrayList<GlobalClass>();
Resources resources = getResources();
mItems.add(new GlobalClass("Whoisthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthsdfdsfis", "Addosdfsdfmg"));
// initialize and set the list adapter
setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}
You need to have ListView in your layout R.layout.neweventdialog_fragment and bind this widget to your view in code, then setAdapter on it.
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
ListView listView = (ListView) view.findViewById(R.id.listView); // you bind to listView your widget
listView.setAdapter(adapter); // you set adapter
builder.setView(view);
return builder.create();
When you wants to appear DialogFragment, you use NewEventDialogFragment.newInstance().show(getSupportFragmentManager(),CURRENT_FRAGMENT_TAG);

2 dynmically created spinners -> but only 1 onItemSelected

i got 2 dynamically created spinners in 1 Activity.
private void populateSpinner() {
AlertDialog.Builder adb2 = new AlertDialog.Builder(this);
LayoutInflater adbInflater2 = LayoutInflater.from(this);
View SpinnerLayout = adbInflater2.inflate(R.layout.spinner, null);
adb2.setView(SpinnerLayout);
adb2.setTitle("Kostenstelle auswählen:");
spinnerKOST = (Spinner) SpinnerLayout.findViewById(R.id.spinner);
List<String> lables = new ArrayList<String>();
lables.add("");
spinnerKOST.setSelection(1, false);
for (int i = 0; i < KostList.size(); i++) {
lables.add(KostList.get(i).getKost());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_dropdown_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKOST.setAdapter(spinnerAdapter);
// use .create to get the AlertDialog
AlertDialog dialog = adb2.create();
// set an OnShowListener
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
spinnerKOST.setOnItemSelectedListener(StaffActivity.this);
}
});
dialog.show();
}
and the second:
private void populateSpinner2() {
AlertDialog.Builder adb2 = new AlertDialog.Builder(this);
LayoutInflater adbInflater2 = LayoutInflater.from(this);
View SpinnerLayout = adbInflater2.inflate(R.layout.spinner, null);
adb2.setView(SpinnerLayout);
adb2.setTitle("Box auswählen:");
spinnerBox = (Spinner) SpinnerLayout.findViewById(R.id.spinner);
List<String> lables = new ArrayList<String>();
lables.add("");
spinnerBox.setSelection(1, false);
for (int i = 0; i < BoxesList.size(); i++) {
lables.add(BoxesList.get(i).getBoxer_mail());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_dropdown_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBox.setAdapter(spinnerAdapter);
AlertDialog dialog = adb2.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
spinnerBox.setOnItemSelectedListener((OnItemSelectedListener) StaffActivity.this);
}
});
dialog.show();
}
they are pretty the same, as you see.
Normally I use for every spinner 1 public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
Before I only had 1 Spinner per Activity and 1 public void onItemSelected.
Now I got 2 Spinner in the Activity but still 1 public void onItemSelected.
How I can use both spinners?
Use two spinner and toggle view viible and invisible between them
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spinner1)
{
//spinner1
}
else if(spinner.getId() == R.id.spinner2)
{
//spinner2
}
}

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

Categories

Resources