I am working on a project in which I need to dynamically add TextView and Spinner as well. I was able to add these two things dynamically from my program.
Now when I was trying to select some items in the Spinner, it was not selecting those items.
Does I need to do anything to make that item selected in Spinner?
for (Map.Entry<String, String> entry : mapColumns.entrySet()) {
spinnerArray = new ArrayList<String>();
final TextView rowTextView = new TextView(cont);
final Spinner spinner = new Spinner(cont);
rowTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
spinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
for(String s: entry.getValue().split(",")) {
System.out.println(s);
s = s.replaceAll("[^a-zA-Z0-9]+","");
spinnerArray.add(s);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(cont, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
rowTextView.setText(entry.getKey());
rowTextView.setTypeface(null, Typeface.BOLD);
spinner.setAdapter(spinnerArrayAdapter);
layout.addView(rowTextView);
layout.addView(spinner);
}
Here mapColumns will hev Key-Value pair. So in the Spinner all the items are getting shown from the Value of that map.
Problem Statement:-
Now I need to make sure if anybody is selecting any items in the Spinner, it should get selected and visible to naked eye.
How can I do that based on my code. Thanks for the help.
Below is the image-
Try use this code :
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(con,
android.R.layout.simple_spinner_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Add an OnItemSelectedListener to your spinner:
spinner.setAdapter(spinnerArrayAdapter);
// add the listener
spinner.setOnItemSelectedListener(this);
Then, implement the listener in your activity:
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
Related
I wrote a simple program that will display an ArrayList and the user can select an item and delete it with a button.
If the user does not select an item but continues to hit the delete button, they will remove the first item on the ArrayList. How do I prevent this from happening? The delete button should only run when an item is selected, so I need to find a way to check for that
int positionID;
ListView listview;
ArrayList<String> valuesArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
valuesArray.add("a");
valuesArray.add("b");
valuesArray.add("c");
valuesArray.add("d");
valuesArray.add("e");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
positionID = (int) id;
}
});
}
public void onClickDelete(View v) {
//need to check if an item is selected. if so, run code below
valuesArray.remove(positionID);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
}
Based on the code you've provided, this is likely happening because the default initialized value for positionID is set to 0. To fix this, you could initialize int positionID = -1 and then in your onClickDelete method, do a check to make sure the positionID is not invalid. Like this:
public void onClickDelete(View v) {
if (positionID < 0) return;
// continue your code here
}
By the way, a few other things you should fix. You should actually interact with adapter directly, so instead of valuesArray.remove(positionID) you should do adapter.remove(positionID). This will automatically update the adapter and refresh the ListView for you so you can get rid of the last two lines of your onClickDelete method.
You can just make valuesArray a local variable in your onCreate method, unless you plan on manipulating it directly elsewhere in your code. If you choose to do that, you can call adapter.notifyDataSetChanged() to make the adapter refresh your ListView.
How can I get the item's text from an adapter's listview?
In my adapter I have this code:
final ArrayList> userList = controller.getAllUsers();
if (userList.size() != 0) {
//Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(PoliceSmsRegisterReceiver.this, userList, R.layout.view_user_entry_register,
new String[]{"userId", "sender", "fullname", "homeaddress", "emailaddress", "phonenumber", "password", "deviceid"},
new int[]{R.id.userId, R.id.viewSender, R.id.viewFName, R.id.viewHAddress, R.id.viewEAddress, R.id.viewPNumber, R.id.viewPassword, R.id.viewA_ID});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
(p.s ; controller is my sqlite db)
then this is my onclick:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
What I want to know is how I can toast the specific string in the adapter when clicking the specific item in the list. Example, I want to toast the viewSender.
You can use AdapterView and position provided by setOnItemClickListener to get any information about clicked item :
Toast.maketext(context,(ModelClass)parent.getItemAtPosition(position).getSpecificText(),Toast.LENGTH_SHORT).show();
You can use int position like this.
Toast.maketext(context,String.valueof(position),Toast.LENGTH_SHORT).show();
An OnItemClickListener handles clicking a list item.
You have to use a custom adapter in which you grab hold of all the Views in the row in getView() and set onClickListeners on them there.
I want to set an alert dialog with list of titles. I have database and table of time table in that.
Time table has column of title. I want to get the list of titles from time table.
I tried some code but it's not working. I have created query in TimeTableHelper to get list of table. But I don't know how to put it in alert dialog.
Can anyone help please?
selectTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimeTableHelper th = new TimeTableHelper(getApplicationContext());
List<String> tables = new ArrayList<String>(th.getTitle());
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddEventActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.alertlistrow, null);
alertDialog.setView(convertView);
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tables);
lv.setAdapter(adapter);
alertDialog.show();
}
});
I am getting error can not resolve constructor ArrayAdapter if I try to add list in this.
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, tables);
How t do this?
You need to pass activity context but inside onClick method this means the onClickListener interface.
Change
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, tables);
to
// Replace MyActivity with the activity you are currently in or getActivity() if inside a fragment
ArrayAdapter adapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_1, tables);
I am in the middle of creating an android app ...I have two Spinner drop down lists. it seems that I cannot get the OnItemSelectedListener to work properly. I get no errors when an item is selected , it just returns null..I spent all day trying to figure out what I did wrong..with no luck.
below is the relevent code.please let me know if you need any more code
//grab the user defined make and model for the listing search
spin_make = (Spinner) findViewById(R.id.spinr_make);
spin_model = (Spinner) findViewById(R.id.spinr_model);
//load the drop downs
ArrayAdapter<String> makeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, make_list);
spin_make.setAdapter(makeAdapter);
//set the item selected listener for the make drop down
spin_make.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
model_list.clear();
new LoadModelListsTask().execute();
ArrayAdapter<String> modelAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, model_list);
spin_model.setAdapter(modelAdapter);
_make = make_list.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have one spinner that populates with my SQL data. This works well. I now want to make it into a dependant spinner where the spinner I already have becomes the second or dependant spinner. I have added another spinner in my MainActivity.java. and it sucessfully retrieves the required mySQL data
#Override
protected void onPostExecute(Void args) {
// Locate spinner1 in activity_main.xml
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
// Spinner adapter
List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));
Collections.sort(typesofjobsunique);
// Locate my spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
Collections.sort(worldlist);
What is the simplest coding approach to migrate from a single to a dependant spinner given the data retrieval itself works well for both spinners and I just want to make it dependant from the current independant format so
spinner1 typesofjobsunique only displays the
mySpinner worldlist
spinner choices from mySQL corresponding to that particular typeofjobunique.
Most of the questions on here relating to dependant spinners, are where the data is in strings.xml which is not very helpful with remote data.
I'm assuming I will need to split my one adapter into two separate adapters, but I am unclear how to proceeed.
From the way that Spinners work, if you want to implement dependence between them, you will need to use the current selection of one (spinner1) as the key for the list source of the other (mySpinner). You should implement an AdapterView.OnItemSelectedListener on spinner1 as recommended in the Spinner guide and set the list in mySpinner. See code below:
// Locate spinner1 in activity_main.xml
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
// Locate mySpinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// **EDIT**
List<String> myWorldList = getWorldListForItem(parent.getItemAtPosition(pos));
Collections.sort(myWorldList);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
myWorldList));
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
Collections.sort(typesofjobsunique);
The implementation for getWorldListForItem() should query your database in the desired way. A hash table could also be used.
Hope that this is useful.
EDIT
Based on your comments, the implementation for getWordListForItem() would look something like this:
List<String> getWordListForItem(String s) {
String json = queryMySQLDatabase(s);
List<String> results = parseJSONintoList(json);
return results;
}
Also, the AdapterView.getItemAtPosition(int pos) function returns a Java object of the type passed into the ArrayAdapter (which is a String in this case). Therefore getWordListForItem() takes a String argument.
As for the "Cannot resolve contructor ArrayAdaptor" error, please check the spelling (it's supposed to be ArrayAdapter not ArrayAdaptor). See ArrayAdapter documentation for more details... I've also fixed my implementation above to sort the list properly.