Spinner returns null - java

The countryCodeSpinner shows up as null in following code snippet.
countryCodeSpinner = (Spinner) findViewById(R.id.spinner_country);
countryCodeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
selectedCountryCode = (Long) selectedItemView.findViewById(R.id.country_name).getTag();
}

Check if you have placed 'setContentView()' method before initializing spinner. Also it can be possible that the resource id is different from which you are using in the same layout file.

Related

How to set selected item for Spinner in Android

In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.
You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Try this snippet
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
int seleccion=parent.getSelectedItemPosition();
spinner.setSelection(position)
});
}
You can select the spinner item based on value instead of position. Can refer the example below-
String value = "to be selected value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (value != null) {
int spinnerPosition = adapter.getPosition(value);
mSpinner.setSelection(spinnerPosition);
}

Set visibility TableLayout based item selected on Spinner

I want to make Spinner to set Visibility of table, i have 2 Array String "cuboid and cylinder". if i select Cuboid , cubeT table is visible and cyclinderT table is Invisible. and if i select Cylinder , cylinderT table is Visible and cubeT is Invisible.
Sample code welcome. Thank you for your time.
You can set an OnItemSelectedListener to your Spinner then using the int position argument to decide what action to take.
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
case Cuboid:
cubeT.setVisibility(View.VISIBLE);
cylinderT.setVisibility(View.GONE);
break;
....
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) { }
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String text = ((Spinner)spinner).getSelectedItem().toString();
if (Intrinsics.areEqual(text, "Cuboid")) {
//Your code here to set your "table" as cubeT if it's image in imageview
//if it's a "tableLayout" you may create 2 different layouts included and..:
setContentView(R.layout.your_cubeT_layout);
} else if (Intrinsics.areEqual(text, "Cylinder")) {
setContentView(R.layout.your_cyclinderT_layout);
}
} //when it comes to use different layouts on the same activity, generally suggestions made over fragments to make your code more dynamic but i don't know how to do that...
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
I'm not using java since years so i might code bad... So no warranty!

Displaying the selected string from Android Spinner

String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
spTimeConsegna = (Spinner)
rootView.findViewById(R.id.timeChooseConsegna);
adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimeConsegna.setAdapter(adapterChooseTimeConsegna);
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
I want to save the selected value of the spinner in the chooseTimeConsegna String, but it always saves the first value of the chooseTime string array indifferently what is choosen in the spinner. Why?
I think you are doing this in onCreate method, so it's only called when that activity is started, not every time you select things on spinner. Try something like this:
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
chooseTimeConsegna = chooseTime[position];
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
This method is gonna be called every time you select something on your spinner, and argument position is the position of the selected item in the spinner.
Replace:
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
With:
spTimeConsegna.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
chooseTimeConsegna = chooseTime[position];
}
});
You should be good to go.

findViewById not working in static function

I found error in findViewById in static function.
my function is--
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
is there any way to solve this error!
can i store value of Spinner in yearName as String
You need to add view inside function as parameter.
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data.
When you call that function add onYearSelect(rootView) here rootView have the layout view.
EDIT 1:
What is View here ?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
You can read more here.
Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});

Android: how to get grid-view item Tag by its position from with-in Another grid-view's set-on-item-click listener function?

How can I get a grid-view's item tag by its position and have to get from another grid-view's item click listener function.
gridview2.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
int i=(Integer)gridview1.getChildAt(gridview1s_position).getTag();---> it is returning Null
}
});
MY gridview1.setOnitemClicklistener and gridview2.setonitemclicklistener are in the same file (MainActivity.java)
But the gridview1 adapter is a ImageAdapter.java(this is for setting the images in the gridview1) and gridview2 adapter is imageadapter2.java(this is for setting black images so that the gridview2 looks like a box with rows and columns, otherwise it is showing like a Bold line because we didn't put anything in the gridview)
gridview1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
int tag=(Integer)gridview1.getChildAt(position).getTag();//this returning the tag
}
});
ImageAdapter1.java
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
if(arg1!=null)
{
imv=(ImageView)arg1;
}
else
{
imv=new ImageView(cont);
imv.setLayoutParams(new GridView.LayoutParams(40,40));
imv.setScaleType(ScaleType.CENTER_CROP);
imv.setPadding(0,0,0,0);
}
imv.setImageResource(imageid[arg0]);//imageid aray is having drawable images
imv.setTag(imageid[arg0]);
return imv;
}
gridview2
gridview2.setOnItemClickListener(new OnItemClickListener()
{
ImageAdapter ia=new ImageAdapter(getApplicationContext());
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
ImageView imv;
if(v!=null)
{
imv=(ImageView)v;
}
else
{
imv=new ImageView(getApplicationContext());
imv.setLayoutParams(new GridView.LayoutParams(40,40));
imv.setScaleType(ScaleType.CENTER_CROP);
imv.setPadding(0,0,0,0);
imv.setBackgroundColor(5555);
}
imv.setImageResource(ia.imageid[tt]);
}
});
using getChildAt might be too cumbersome for something like this because it only useful for making references to views that are in view and re-orders its indexes to match this. I don't know enough about where your other GridView is positioned to pursue this avenue further.
But regardless, the way i'd do something like this is to make an intermediary collection between the two adapters. as in one adapter holds all the tags in an indexed collection and then you could make some sort of reader get method. at the very least, this way of doing it would put my mind at ease.
gridview2.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int i = gridview1.getTagFromPosition(position);
}
});
then in the gridView1 adapter something like:
private int[] tagCollection;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// .....
convertView.setTag(tagCollection[position]);
return convertView;
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
i at least hope the idea comes across so that you can modify it for however is practical for how your objects are getting modified and accessed.
Finally myself i got the solution for my question.Thank you for all who gave their valuable suggestions.
i saved the tag of a particullar cell of grid-view1 in a variable and used that variable in the grid-view2.

Categories

Resources