I've created an array list and display it in a list view with simple list item multiple choice but i cannot check or tick the items on the list, when i click on the items nothing happens. Please check my code below and tell me what i am doing wrong.
package com.example.arrays;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity {
ListView showList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show = (TextView)findViewById(R.id.txtShow);
final Random generate = new Random();
showList = (ListView)findViewById(R.id.listView1);
final String[] myAttraction = new String[4];
myAttraction[0]= "Walter Sisulu National Botanical Garden ";
myAttraction[1]= "Coca-Cola Dome";
myAttraction[2]= "Promusica Theatre";
myAttraction[3]= "Unisa Science Campus";
Button arrays = (Button)findViewById(R.id.button1);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
}
});
showList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add a OnItemClickListener like this to check/uncheck the CheckedTextView when user click on an item
showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// change the checkbox state
CheckedTextView checkedTextView = ((CheckedTextView)view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
change your code as following....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
}
});
showList.setOnItemClickListener(new OnItemClickListener() {
public boolean onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
Set choiceMode property of your list to multipleChoice. I'm implementing multiple choice list in such a way in my applications, and it surely works.
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
To this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
showList.setAdapter(adapter);
Just Add this line if you have a ListView and have selected simple_list_item_multiple_choice and you are unable to interact with the checkbox.
YourListViewName.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Related
please I'm trying to add understand how to add onItemClickListener to the followng code such that when "Smartphone Plans" is clicked, its activity starts and so on. I've seen other questions on StackOverflow relating to this question but do not understand how to go about them.
I've already added an onItemClickListener but do not understand how to set it to specific list items.
here is the code
package devchuks.com.rechargeit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EtisalatData extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etisalat_data);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"Smartphone Plans",
"Internet Bundles",
"Weekend Plans",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
You can define your listView.setOnItemClickListener like this to go to different activity for clicking different element.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = listView.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
if(position==0) {
// Do your code for clicking "Smartphone Plans" example
// startActivity(new Intent(getApplicationContext(),SmartphonePlans.class));
}
else if(position==1) {
// Do your code for clicking "Internet Bundles". example
// startActivity(new Intent(getApplicationContext(),InternetBundles.class));
}
else if(position==2) {
// Do your code for clicking "Weekend Plans". example
//startActivity(new Intent(getApplicationContext(),WeekendPlans.class));*/
}
});
onItemClick will be called whenever any of the list items are clicked. The position will be the position of the view in the Adapter.
Please refer -
How to handle the click event in Listview in android?
Thanks
Sriram
try this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = values[position];
if(text.equals("Smartphone Plans")){ //your specific list item text
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
i.putExtra("TEXT", text);
startActivity(i);
}
}
}
If this helps and is your concern
`
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = values[position];
switch(data){
case "Smartphone Plans":
// do somwthing
break;
// similarly for other two values.
}
}
});`
Below method give you a position of a clicked row. Take advantage of that and value from your array.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Move your values array to member array or make it final to use
// in Anonymous class
final String selectedValue = values[position];
Intent intent = null
// Now add case and start activity
if("Smartphone Plans".equals(selectedValue)) {
intent = new Intent(EtisalatData.this, SmartPhonePlan.class);
}
else if("other Plans".equals(selectedValue)){
// other action
}
//... more cases and at the end start your activity if its not null
startActivity(intent);
}
I am trying to add a click function to a programmatically filled List View. I followed a tutorial, and it gives me no errors and to my understanding it should work, however when I tap a cell it does completely nothing. No crash/action occures.
This is my code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class domainViewer extends ActionBarActivity {
public List<Domain> domains = new ArrayList<Domain>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_domain_viewer);
populateDomainList();
populateViewList();
RegisterClickCallback();
}
private void populateViewList() {
ArrayAdapter<Domain> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setAdapter(adapter);
}
private void populateDomainList() {
domains.add(new Domain("cheese.com", true, "€15,50" , R.drawable.deselected));
domains.add(new Domain("cheese.nl", true, "€15,50" , R.drawable.deselected));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_domain_viewer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyListAdapter extends ArrayAdapter<Domain> {
public MyListAdapter() {
super(domainViewer.this, R.layout.item_view, domains);
}
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Domain currentDomain = domains.get(position);
ImageView imageView = (ImageView)itemView.findViewById(R.id.imgSelected);
imageView.setImageResource(R.drawable.deselected);
TextView domainText = (TextView) itemView.findViewById(R.id.tvDomain);
domainText.setText(currentDomain.getDomain());
TextView priceText = (TextView) itemView.findViewById(R.id.tvPrice);
priceText.setText(currentDomain.getPrice());
return itemView;
//return super.getView(position, convertView, parent);
}
}
private void RegisterClickCallback() {
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Domain clickedDomain = domains.get(position);
String message = position + " - " + clickedDomain.getDomain();
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
You need to implement the click event with in your adapter class ,
public OnItemClickListener onItemClick = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
}
};
Then create the listener where you set the adapter,
private void populateViewList() {
ArrayAdapter<Domain> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setAdapter(adapter);
list.setOnItemClickListener(adapter.onItemClick);
}
the adapter works fine, but i don't understand why the position in OnItemClick is always "0"
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int pos=position;
}
});
Don't ask me why, but the argument position in method OnItemClickListener.onItemClick holds the index relative to the AutoCompleteTextView's dropdown list, not the position in your adapter array (in your case regions)!
So, to find the item's real position you must get the string selected in the dropdown and find its index in the adapter array:
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
int pos = Arrays.asList(regions).indexOf(selected);
}
});
I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:
public class Country extends Object {
public int id;
public Country(int id) {
this.id = id;
}
#NonNull
#Override
public String toString() {
switch (id) {
case 0:
return "Albania";
case 1:
return "Romania";
case 2:
return "Ucraina";
case 3:
return "Russia";
default:
return "Unknwon";
}
}
}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
new Country(0),
new Country(1),
new Country(2),
new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
int nItems = ada.getCount();
// default Country unknown
Country selItem = new Country(5);
if (nItems > 0) {
selItem = (Country) ada.getItem(0);
}
Log.d(TAG,
"onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
+ ", selItem.id=" + selItem.id);
}
});
...
Logs:
when the AutocompleteTextView value matches an item in the dropdown:
onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2
when the value is blank:
onClick(): nItems=4, selItem.name=Albania, selItem.id=0
when the value isn't blank but doesn't match any item in the dropdown:
onClick(): nItems=0, selItem.name=Unknown, selItem.id=5
You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.
I put this in a simple example and it works correctly for me. See below:
package com.example.autocompletetv;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class AutoCompleteActivity extends ListActivity {
public static final String TAG = AutoCompleteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete);
String[] regions = {"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "postion was " + position);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_complete, menu);
return true;
}
}
When I click I get:
12-09 19:13:30.617: I/AutoCompleteActivity(1883): postion was 2
12-09 19:13:31.997: I/AutoCompleteActivity(1883): postion was 3
12-09 19:13:34.687: I/AutoCompleteActivity(1883): postion was 4
12-09 19:13:37.028: I/AutoCompleteActivity(1883): postion was 0
List_Remind.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" >
<TextView
android:id="#+id/label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello"
android:layout_weight="1"
android:textSize="30px" >
</TextView>
<ImageButton
android:background="#null"
android:id="#+id/imageButton1"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginRight="10dp"
android:src="#drawable/delete_task" />
</LinearLayout>
ReminderListActivity.java
package com.dummies.android.taskreminder;
import com.dummies.android.taskreminder.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class ReminderListActivity extends Activity implements OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private RemindersDbAdapter mDbHelper;
ListView lvRemind;
ImageButton btnAdd,btnBack,btnSettings;
TextView text;
LinearLayout layout;
ArrayAdapterExample aAdapter;
int pos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// setContentView(R.layout.reminder_list);
LayoutInflater inflate = LayoutInflater.from(this);
layout = (LinearLayout)inflate.inflate(R.layout.main, null);
this.setContentView(layout);
btnAdd = (ImageButton) findViewById(R.id.btnAdd);
btnBack = (ImageButton) findViewById(R.id.btnBackMain);
btnSettings = (ImageButton) findViewById(R.id.btnSettings);
btnAdd.setOnClickListener(this);
btnBack.setOnClickListener(this);
btnSettings.setOnClickListener(this);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
lvRemind.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
// Intent i = new Intent(ReminderListActivity.this, ReminderEditActivity.class);
// i.putExtra(RemindersDbAdapter.KEY_ROWID, arg2);
// startActivityForResult(i, ACTIVITY_EDIT);
// Toast.makeText(ReminderListActivity.this, "Hello", Toast.LENGTH_LONG).show();
}
});
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
// SimpleCursorAdapter reminders =
// new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
// setListAdapter(reminders);
text = (TextView)findViewById(R.id.TextView02);
lvRemind = (ListView)findViewById(R.id.alist);
aAdapter = new ArrayAdapterExample(ReminderListActivity.this, mDbHelper.fetchAllReminders());
lvRemind.setAdapter(aAdapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_delete:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteReminder(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createReminder() {
Intent i = new Intent(this, ReminderEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
// #Override
// protected void onListItemClick(ListView l, View v, int position, long id) {
// super.onListItemClick(l, v, position, id);
// Intent i = new Intent(this, ReminderEditActivity.class);
// i.putExtra(RemindersDbAdapter.KEY_ROWID, id);
// startActivityForResult(i, ACTIVITY_EDIT);
// }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
createReminder();
break;
case R.id.btnSettings:
Intent i = new Intent(this, TaskPreferences.class);
startActivity(i);
break;
case R.id.btnBackMain:
onBackPressed();
break;
default:
break;
}
}
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
}
class ArrayAdapterExample extends CursorAdapter {
public ArrayAdapterExample(Context context, Cursor c) {
super(context, c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView textViewPersonName = (TextView) view.findViewById(R.id.label);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
Log.d("Index: ", ""+cursor.getPosition());
pos = cursor.getPosition();
ImageButton ibDel =(ImageButton)view.findViewById(R.id.imageButton1);
ibDel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(ReminderListActivity.this, "Hello", Toast.LENGTH_SHORT).show();
lvRemind.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(ReminderListActivity.this, ""+lvRemind.getItemAtPosition(arg2), Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.list_remind, parent, false);
return retView;
}
}
}
How can I delete particular item from custom listview. I have added button in custom listview. I want to delete item using particular button on that position.
As for deleting stuff, you need to delete from the ADAPTER not a list. You don't need to keep your own copy of the items (unless you are using them for something else) because there is a list of item inside the array. you need to call adapter.remove(item) instead of list.remove(item)
Well you just remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
Hi try the following code to delete the Item from Listview
Button button1 = (Button) findViewById(R.id.create_message);
button1.setOnClickListener(new OnClickListener()
public void onClick(View v)
{
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}
}
});
I am new to Android Development so the query may seem novice.
I was trying to make an app where there are a couple of spinners and after the user selects one spinner the other spinner gets filled up with the data based on the selection in spinner1.
ie. First user selects Country. Based on country the spinner 2 gets filled up with states and based on the state the spinner 3 gets filled up with cities.
I have created all the countries as a string arrays in strings.xml like -
<string-array name="Country">
<item >USA</item> etc...
Similarly states have been created in the string.xml as - (Each Country is a separate entry with a naming convention as (country name)_(States)
<string-array name="USA_state">
<item >New York</item> etc...
Now I want the second spinner to populate based in country selection. Hence the formula used by me is to the get the second spinner is -
String getstate = country[index]+"_"+"state";
state=getResources()
.getStringArray(getResources().
getIdentifier(getstate,null,getPackageName()));
When I run this app the Manactivity just shows a blank screen and I donot get any Debug info and get an error "the jar file android.jar has no source attached".
Please help. The complete mainActivity is given below -
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.view.View;
public class MainActivity extends Activity {
String[] country;
String[] state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country = getResources().getStringArray(R.array.country);
Spinner country_spinner =(Spinner) findViewById(R.id.country);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+"country", Toast.LENGTH_SHORT).show();
Fill (index);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
protected void Fill(int index) {
// TODO Auto-generated method stub
//Field resField=R.array.getField(country[index]);
//int getstate = resField.getInt(null);
String getstate = country[index]+"_"+"state";
state=getResources().getStringArray(getResources().getIdentifier(getstate,null,getPackageName()));
Spinner state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state);
state_spinner.setAdapter(adapter);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index2 = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),"You Have Selected "+state[index2] + " statet",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
I was able to solve the problem. The final code is given below. This is a nested approach so if there are 3 spinners (like city after state) do we again nest the code for that spinner? Is there any simpler method?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+" County", Toast.LENGTH_SHORT).show();
final CharSequence[] state_array = state.getTextArray(index);
final Spinner state_spinner =(Spinner) findViewById(R.id.state);
ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(MainActivity.this, android.R.layout.simple_spinner_item, state_array);
state_spinner.setAdapter(adapter1);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
final int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+state_array[index]+" State", Toast.LENGTH_SHORT).show();
});
}
public void onNothingSelected(AdapterView<?> arg0) {
state_spinner.setAdapter(null);
}
});