Spinners and Android - java

I would like to take the value of a spinner and convert it to a String to play about with.
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
s1.setOnItemSelectedListener((OnItemSelectedListener) this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
I thought somthing like this would work....
private OnClickListener sendClickListener = new OnClickListener(){
public void onClick(View arg0) {
EditText dstName = (EditText) findViewById(R.id.destinationAddress);
EditText dstLanguage = (EditText) findViewById(R.id.spinner1);
String address = dstName.getText().toString();
String language = dstLanguage.getText().toString();
ops.createSocketConnection(language, address);
Notification notification = new Notification();
notification.vibrate = new long[] {100};
}};
Allas it does not....
I have looked at a few examples however I am not sure If they are directly related to my question.
Thanks in advance!

Try this:
OnItemSelectedListener itemSelectedHandler = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
String str = parent.getItemAtPosition(pos).toString();
// Do whatever you want with the string
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
//set the spinner's listener for select event
mSpinner.setOnItemSelectedListener(itemSelectedHandler);

Hmm, I'm not entirely sure what the question is, but if the issue is getting the value of a spinner, check out Spinner data to string:
You can use getSelectedItem to
get the currently selected item. If
you've bound to an
ArrayAdapter<String>, this will
be the value.
Of course, in this instance you're returning CharSequence, so you'd do
String strVal = getSelectedItem().toString();
Hope this helps,
Phil Lello

Related

Pass a variable to a different method?

hello I am making a bmi calculator i want it to work based on 3 variables, weight height and gender.
The gender in on a spinner which lets the user choose:
final Spinner spinner = view.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),R.array.gender, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
The problem is the spinner uses a whole new method for it to work:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String gendertext = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), gendertext,Toast.LENGTH_SHORT).show();
}
i want to take that variable gendertext and use it on this part of code which is inside the onCreateView
edit_height = (EditText) view.findViewById(R.id.edit_height);
edit_weight = (EditText) view.findViewById(R.id.edit_weight);
button_calculate_bmi = (Button) view.findViewById(R.id.button_calculate_bmi);
text_results = (TextView) view.findViewById(R.id.text_results);
button_calculate_bmi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
String results = "Results:";
float height = 0;
float weight = 0;
try {
height = Float.parseFloat(edit_height.getText().toString());
weight = Float.parseFloat(edit_weight.getText().toString());
} catch (Exception ex) {
Context context = getActivity();
CharSequence text = "You forgot to enter something";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
height = height/100;
float bmi = weight / (height * height);
text_results.setText(results+bmi);
}
});
return view;
}
thank you in advance!
You can create the genderText variable outside of all methods in the Activity and initialize it to the first item in your R.array.gender. When the value in spinner is changed, onItemSelected is called and you get the updated value which you can set to the variable genderText.
Then in the button OnClickListener you can use the genderText variable.

without selecting how to pass the spinner value

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) {
}
});

Getting data from activity into RecyclerView adapter?

Intent i = getIntent();
Bundle myBundle = i.getExtras();
date1 = myBundle.getString("Date1");
date2 = myBundle.getString("Date2");
user = myBundle.getString("UserName");
chain = myBundle.getString("ChainName");
shop = myBundle.getString("ShopName");
product_g = myBundle.getString("ProductGroup");
product_c = myBundle.getString("ProductCategory");
product = myBundle.getString("Product");
count = myBundle.getInt("Count");
type_c = myBundle.getInt("CountType");
price = myBundle.getInt("Price");
type_p = myBundle.getInt("PriceType");
inch = myBundle.getInt("Inch");
promotor = myBundle.getInt("Promotor");
I need these variables in recycler adapter to make retrofit request in RecyclerView adapter.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
android.app.AlertDialog.Builder mBuilder = new android.app.AlertDialog.Builder(context);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.sales_filtered_shop_pop_up, null);
final RecyclerView rd3 = (RecyclerView) mView.findViewById(R.id.sales_rv);
Button mClose = (Button) mView.findViewById(R.id.sales_pop_up_btn_close);
mBuilder.setView(mView);
final android.app.AlertDialog dialog = mBuilder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(false);
// here
dialog.show();
mClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
This is my RecyclerView adapter item click. I need the variables in // here to make Retrofit api call.
Intents are for communication between activity, what you need to do is to create a simple function in your adapter, and then call in the activity.
Adapter:
private String date1;
private String date2;
public void setData(String date1, String date2, ...) {
this.date1 = date1;
this.date2 = date2;
...
}
Activity:
adapter.setData(date1, date2, ..);
(I can't use the comment yet but)
The idea which #DoubleD wrote is the right one, all you need to do is to create a function (much like a constructor) that will receive your data in the adapter class.
The NullPointerException you are getting isn't from the function, check your data.
And I will suggest to create a custom object that will hold those things (depend on your goal).
Check this answer. Here you will have your onClickListener() in your Activity.
Simple Android RecyclerView example

OnClickListener doesn't work as expected

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) {
}
});

AdapterView not found [Spinner]

I'm currently on my first Spinner. But I kinda got stuck during the onItemSelectedListener, since I cannot implement it. I first tried to follow the method of CommonWares book but it would work - but my method now doesn't work either.
At first I tried to let my activity implement the AdapterView directly - but the only consequence was that eclipse told me that the interface AdapterView is not available and asked me to create it ... however I got the very same error now again.
public class Lunchplace extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mensa);
Context c = getApplicationContext();
Spinner dateSelection = (Spinner)findViewById(R.id.date);
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.)
// get all the little tidbits of extra informations
Bundle extras = getIntent().getExtras();
String location = extras.getString("Mensa");
// this function will download the Lunchfile - if necessary
Data lunchData = new XMLData(c);
// set the header text
TextView mensaname = (TextView)findViewById(R.id.header);
mensaname.setText(location);
// get the spin view out of the xml
Spinner spin = (Spinner)findViewById(R.id.date);
// attach it to an adapter
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.days, android.R.layout.simple_spinner_item);
// I should be able to put a custom layout of the spinner in there.. I bet
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnClickListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
// set the current day of the week as the default selection
spin.setSelection(Tools.getDayOfWeek());
// get the tablelayout
TableLayout tl = (TableLayout)findViewById(R.id.MenuTable);
lunchData.getMenuforDay(c,tl,location);
TextView counterTV = new TextView(c, null, R.style.MenuField);
}
}
Does anybody have any Idea on how I can solve that problem?
There is nothing special with implementing the OnItemSelectedListener. Try smth like this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ("YourDayToHandle".equals(spinner.getSelectedItem())) {
// do smth useful here
}
}
public void onNothingSelected(AdapterView<?> parent) {}
});

Categories