android Spinner followed by ListView - onItemSelected not called - android

I have had a good search around and can't seem to find an answer. The method onItemSelected is not being called. Here's the code featured in my activity's onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_trips);
try {
// if network present.. TODO
// Load Devices
deviceList = new ArrayList<Device>();
DataAsyncTask loadDevices = new DataAsyncTask(0);
loadDevices.execute(someUrl);
List<Device> deviceListNames = deviceList;
final ListView tripListView = (ListView)findViewById(R.id.trip_list);
Spinner deviceSpinner = (Spinner) findViewById(R.id.select_device_spinner);
ArrayAdapter<Device> deviceAdapter = new ArrayAdapter<Device>(this, android.R.layout.simple_spinner_dropdown_item, deviceListNames);
deviceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deviceSpinner.setAdapter(deviceAdapter);
OnItemSelectedListener spinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int i, long id) {
Log.d(TAG, "select is: " + parent.getSelectedItem().toString());
DataAsyncTask loadTrips = new DataAsyncTask(1);
loadTrips.execute(someUrl);
ArrayAdapter<Trip> tripAdapter = new ArrayAdapter<Trip>(getApplication(),
android.R.layout.simple_list_item_1, tripList);
tripListView.setAdapter(tripAdapter);
tripListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int i, long id) {
Log.d(TAG, parent.getSelectedItem().toString());
Intent intent = new Intent(getApplication(), TripSummary.class);
//put value of tripId to intent TODO
startActivity(intent);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO
Log.d(TAG, "nothing selected");
}
};
deviceSpinner.setOnItemSelectedListener(spinnerListener);
} catch (Exception e){
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
Here's the activity's layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewTrips" >
<Spinner
android:id="#+id/select_device_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_device"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:drawSelectorOnTop = "true" />
<ListView
android:id="#+id/trip_list"
android:layout_below="#id/select_device_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/trips"
android:clickable="true" />
</RelativeLayout>
It's values are populated and displaying correctly in the Spinner. I am just having an issue with the onItemSelected method in the OnItemSelectedListener() which is set to deviceSpinner - this method is then supposed to populate the ListView, where once clicked takes the user to a new activity. Can anyone explain what I am doing wrong?
I have also tried implementing OnItemSelectedListener for the activity, which doesn't work either.
Note: There's no errors to report in LogCat,
Log.d(TAG, "select is: " + parent.getSelectedItem().toString());
is not printing.
Thanks

Related

ArrayList doesn't show up on Spinner

I was trying to create a spinner which display a list of data from array list.
When I clicked on the dropdown it displays the list, but when I clicked on an item inside the dropdown list it doesn't show up the value on the spinner.
Am I missing something here?
Note: Yesterday I have tried to check using Log.d() and System.out.println, itemOnSelected() doesn't but today it works fine. Maybe I rebuilding the project or I have changed something in the code but the value on the spinner still doesn't show up after I clicked on the item inside the spinner.
Spinner spnSubjectIDInfo;
ArrayList<String> subjectList;
ArrayAdapter<String> adpSubj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
spnSubjectIDInfo = (Spinner) v.findViewById(R.id.spnSubjectIDInfo);
adpSubj = new ArrayAdapter<String>(MyActivity.this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnSubjectIDInfo.setAdapter(adpSubj);
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
XML
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />
Try this
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this, subjectList.get(position).toString() " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
You are passing the wrong context to Toast instance:
If your code is in Activity then replace this by YourActivity.this or if it's in Fragment then use getActivity() or use Application context getApplicationContext(). Because currently, this is representing Spinner's onItemSelected listener context.
Do :
Toast.makeText(/*Your activity/application context*/, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
instead of:
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
Change the "this" to "ActvityName.this" or use "getApplicationContext()" in the Toast, you are passing anonymous class context in the toast.
Like below:
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this,parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hope this will help you.
public class SpinnerTest extends AppCompatActivity {
private ArrayList<String> subjectList;
private ArrayAdapter<String> adpSubj;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner= (Spinner) findViewById(R.id.spnSubjectIDInfo);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
adpSubj = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adpSubj);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), spinner.getItemAtPosition(position).toString() + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
in Spinner setOnItemSelectedListener methord not work. if you want to get selected value show in toast use this line
String Text = mySpinner.getSelectedItem().toString();
Toast.makeText(this,Text,Toast.LENGTH_LONG).show();
it will return the selected value and will be displayed on Toast.
After few more searching I realized that I have to set the width size of the spinner to wrap_content as the length of the value doesn't support to display it on the spinner after the item being clicked at.
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />

How to open different activities on item selected on drop down menu on the toolbar

I have searched for this over the internet and haven't found appropriate answers. I am loading a spinner drop down menu on my toolbar which contains items that open different activities after being selected. So far I have been able to create a toast which returns the name of the selected item. But I would like to open different activities for each item on the menu. I know this might be a duplicate somewhere but their answers haven't worked for mine yet.
This is my spinner:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/primaryColor"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<Spinner
android:id="#+id/spinner_nav"
android:layout_width="wrap_content"
android:gravity="bottom"
android:layout_height="wrap_content"></Spinner>
</android.support.v7.widget.Toolbar>
And this is my MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
final Spinner spinner_navs = (Spinner) findViewById(R.id.spinner_nav);
SpinnerAdapter mSpinner = ArrayAdapter.createFromResource
(this, R.array.action_bar_spinner, android.R.layout.simple_spinner_dropdown_item);
spinner_navs.setAdapter(mSpinner);
spinner_navs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I know I am a newbie, but any help on this I would appreciate it. Thanks in advance.
Use this
spinner_nav.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
if(position==0){
// open activity 1
}else if(position==1){
// open activity 2
}
else if(position==2){
// open activity 3
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Use a Switch statement
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
switch (position) {
case 1:
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("yourkeyone", string);
break;
case 2:
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("yourkeytwo", string);
break;
//ect...
}
return true;
}

custom spinner with last item as a link

I want a Spinner which contains last Item as "Add more items"
and when i click on it, then i can add next item. The item i have added should get displayed in spinner list and will have same last item as "Add more items"..
I tried using Adapter but how can i keep last element as "Add more items"
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == spinner.getItemIdAtPosition(spinner.getCount()))
// my code for adding item to list using Adapter
else
// spinner.setSelection();
}
did i wrote anything wrong??
any help??..Thanks ...
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dropDownVerticalOffset="2dp"
android:dropDownWidth="500sp"
android:spinnerMode="dropdown" />
</RelativeLayout>
MainActivity.java :
public class MainActivity extends Activity {
private Spinner spinner;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
data.add("item " + i);
}
data.add("Add New Item");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
tv.setText(spinner.getSelectedItem().toString());
if (spinner.getSelectedItem().toString().equals("Add New Item")) {
data.remove(position);
data.add(position, "item " + position);
data.add((position + 1), "Add New Item");
updateAdapter(data);
Toast.makeText(getApplicationContext(), "item " + position,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
public void updateAdapter(ArrayList<String> data) {
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
data);
adapter.notifyDataSetChanged();
}
}

Android: items on ListView changes background color after click

I've a problem with ListView. I have a ListView with some items(for example, two have green background color, and rest have white. When I click on item, the rest of items changes colors to white.
Example1:
Item1(white)
Item2(green)
Item3(white)
Item4(green)
When I click on Item3 this look like:
Item1(green)
Item2(white)
Item3(green)
Item4(white)
Example2:
Item1(white)
Item2(green)
Item3(white)
Item4(white)
When I click on Item3 this look like:
Item1(white)
Item2(white)
Item3(green)
Item4(white)
What can I do to fix it?
EDIT:
This is my code
onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
devicesList = (ListView) findViewById(R.id.pairedDevicesListView);
devices = DatabaseHandler.getInstance().getCounters(false);
adapter = new ArrayAdapter(this, R.layout.text_view_layout, devices);
devicesList.setAdapter(adapter);
devicesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("Click " + devicesList.getItemAtPosition(i));
}
});
}
Adding items to ListView:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Broadcast Receiver");
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
for(int i = 0; i < devicesList.getCount(); i++) {
if(device.getName().equals(devices.get(i))) {
View v = devicesList.getChildAt(getItemPosition(device.getName()));
v.setBackgroundColor(Color.GREEN);
}
}
}
}
};
EDIT2
ListView xml
<ListView
android:layout_width="match_parent"
android:layout_height="167dp"
android:id="#+id/pairedDevicesListView"
android:layout_gravity="center_horizontal"
android:layout_weight="0.66"
android:choiceMode="singleChoice" />
text_view_layout
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textviewlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"></TextView>
You can do something like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(dbManager.toggleCheck(list,parent.getItemAtPosition(position).toString()) == 1){
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#2196f3"));
}
else {
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#e3f2fd"));
}
}
});

Display one array value according to other array

I have created to arrays.One is for all the states(Full Form) in USA and other is the all short form of the states in USA.I have dispayed the states(Full form) in a spinner.Now what i have to do is display the state in short form according to which the user selects in the spinner.How can i achieve it.
You should use mapping i.e in both the arrays the elements should be mapped. Let me give you an example.
String[] fullForm = { Alabama, California, Florida, Illinois};
String[] shortForm = {AL, CA, FL, IL};
ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,fullForm );
spinner.setAdapter(ad);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), " You selected " + fullForm[position] + "\n Short form is : " + shortForm[position], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// try this way,hope this will help you...
**activity_main.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Spinner
android:id="#+id/spnState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
**MainActivity.java**
public class MainActivity extends Activity {
Spinner spnState;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
spnState = (Spinner) findViewById(R.id.spnState);
String[] stateFullNameArray = new String[]{"statefullname1","statefullname2","statefullname3","statefullname4","statefullname5"};
final String[] stateShortNameArray = new String[]{"stateshortname1","stateshortname2","stateshortname3","stateshortname4","stateshortname5"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,stateFullNameArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnState.setAdapter(adapter);
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,stateShortNameArray[position],Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

Categories

Resources