The user types 2 letters in the autocomplete text box
Those 2 letters get saved and used in a web service method in order to
retrieve all users who start with those 2 letters
XML result get returned, and get parsed, and we retrieve the user name+ the id and
save each one in different ArrayList
the result from the first name arraylist get puts in an a dropdown list (the autocomplete one)
The user select an item from the drop list items
--
I need to display the name in the drop down list, however, when the user chooses a name, that user ID should be selected and saved as a String in order to be used for another query.
Question is: How to display the name but select the ID for that name
AutoCompleteTextView assigneeInput;
assigneeInput=(AutoCompleteTextView)
findViewById(id.editassignee);
assigneeInput.addTextChangedListener(new
TextWatcher() {
#Override
public void onTextChanged (CharSequence s,int start, int before, int count){
getContactsForAssignee();
}
#Override
public void beforeTextChanged (CharSequence s,int start, int count, int after){
}
#Override
public void afterTextChanged (Editable s){
}
}
);
//Textwatcher for assignee input -end
}
//Method to get Contacts for the assignee autocomplete - Start
public void getContactsForAssignee() {
//webservice call method
}
//Method to get Contacts for the assignee autocomplete - End
public void receiveResults10(String result10) {
try {
//Dom parsing set up
List<String> valSetOne = new ArrayList<String>();
List<String> valSetTwo = new ArrayList<String>();
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < nodesUDSObjectList.getLength(); i++) {
Element elementUDSObject = (Element) nodesUDSObjectList.item(i);
NodeList nodesAttributeList = elementUDSObject.getElementsByTagName("Attribute");
HashMap<String, String> mapp = new HashMap<String, String>();
for (int iA = 0; iA < nodesAttributeList.getLength(); iA++) {
Element elementAttribute = (Element) nodesAttributeList.item(iA);
//You have attribute(iA)
NodeList AttrNameElementList = (NodeList) elementAttribute.getElementsByTagName("AttrName");
String nameValue = getCharacterDataFromElement((Element) (AttrNameElementList.item(0)));
System.out.println("name" + nameValue);
NodeList AttrValueElementList = (NodeList) elementAttribute.getElementsByTagName("AttrValue");
String valueValue = getCharacterDataFromElement((Element) (AttrValueElementList.item(0)));
if (nameValue.equals("name")) {
valSetOne.add(valueValue);
mapp.put(COMBO_NAME, valueValue);
}
if (nameValue.equals("id")) {
valSetTwo.add(valueValue);
mapp.put(PERSISTENT_ID, valueValue);
}
}
menuItems.add(mapp);
}
AutoCompleteTextView editAssignee;
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, valSetOne);
editAssignee = (AutoCompleteTextView) findViewById(R.id.editassignee);
editAssignee.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
}
//Beginning of method to actually save the ticket executed on click of the "save" button
public void SaveThisIncident(View v) {
AutoCompleteTextView editAssigneeInput = (AutoCompleteTextView) findViewById(R.id.editassignee); //receiving the users input for assignee
String thisIsAssignee = editAssigneeInput.getText().toString();
}
You need to set itemclicklistner for your AutoCompleteTextView editAssignee & use BaseAdapter instead of ArrayAdapter.
Pass ArrayList of your custom object which contain both id & string value to baseadapter.
Custom object can be
public class item{
String id;
String value;
}
Now onClickItem you can get both id & value from your Arraylist
Related
I m trying to override my JComboBox getSelectedItem method using this static method :
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
// query to select ID and TITLE from profiles table
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
ArrayList visualItems = new ArrayList(); // the Items of my combobox [item1,item2]
ArrayList idItems = new ArrayList(); // the corresponding IDs for each item [id1,id2]
while (myJComboResultSet.next()) {
visualItems.add(myJComboResultSet.getObject("TITRE")); // filling items set
idItems.add(myJComboResultSet.getObject("ID")); // filling IDs set
}
System.out.println("IDItems=" + idItems); // checking that my Items are filled
System.out.println("visualItems=" + visualItems); // checking that my IDs are filled
// creating a combobox of previous items
jComboBox = new JComboBox(visualItems.toArray()) {
ArrayList values = idItems;
// overriding the getSelectedItem to return the corresponding selected item's ID
#Override
public Object getSelectedItem() {
Object get = values.get(super.getSelectedIndex());
System.out.println("get = " + get);
return get;
}
};
}
I m calling this method from another frame :
JComboBoxTools.setupID_TITLE_ComboBox(J_Users_Profile,"profiles");
But when executed it don't work.
the output :
visualItems=[Admin,Teacher,Student]
IDItems=[0,3,5]
the selected item return value is : Teacher
Don't know what to do I want it to return 3 wich is the ID of teacher.
the full project is under : this link
thank you.
I get my desired values using a mapComboBoxModel
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
HashMap myMap = new HashMap();
while (myJComboResultSet.next()) {
myMap.put(myJComboResultSet.getObject("TITRE"), myJComboResultSet.getObject("ID"));
}
jComboBox.setModel(new MapComboBoxModel(myMap) {
#Override
public Object getValue(Object selectedItem) {
return map_data.get(selectedItem); //To change body of generated methods, choose Tools | Templates.
}
});
}
I overrided getValue to return the ID .
if (myComponent instanceof JComboBox) {
JComboBox jComboBox = (JComboBox) myComponent;
MapComboBoxModel model = (MapComboBoxModel) jComboBox.getModel();
values+=""+model.getValue(model.getSelectedItem())+",";
}
I'm working on an Android App (Too order objects) for school and I want to make a Spinner with categories labels.
However, when a label is selected, I want to get the selected category's id too.
I already can get my data into JSON thanks for my webservice but I don't know how to do to make my own custom adapter for my spinner.
The JSON looks like this :
[{"id":"1","name":"VEHICULES","subcategories":
[
{"id":"1","name":"Voitures"},
{"id":"2","name":"Motos"},
{"id":"3","name":"Equipement auto"},
{"id":"4","name":"Equipement moto"},
{"id":"5","name":"Autres"}]
},
{"id":"2","name":"IMMOBILIER","subcategories":
[
{"id":"6","name":"Locations"},
{"id":"7","name":"Colocations"},
{"id":"8","name":"Autres"}]
}]
Searching to make my own adapter, I created a java class Categories like that :
public class Categories {
public int id;
public String name;
public Categories(int id, String name) {
this.id = id;
this.name = name;
}
}
And, on my fragment I can get my JSON and read it :
public class AttemptCategories extends AsyncTask<String, String, String> {
String categoriesURL = "http:blabla.com";
JSONArray dataJsonArr = null;
JSONArray dataJsonArr2 = null;
List<Categories> listCat = new ArrayList<>();
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0Z) {
try {
JSONObject json = jsonParser.getJSONFromUrl(categoriesURL);
dataJsonArr = json.getJSONArray("categories");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Categories cat = new Categories(Integer.parseInt(c.getString("id")), c.getString("name"));
listCat.add(cat);
dataJsonArr2 = c.getJSONArray("subcategories");
for(int j = 0; j < dataJsonArr2.length(); j++) {
JSONObject s = dataJsonArr2.getJSONObject(j);
Categories subcat = new Categories(Integer.parseInt(s.getString("id")), s.getString("name"));
listCat.add(subcat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
adapter = new ArrayAdapter<>(getActivity().getApplicationContext(), 0, listCat);
sCategories.setAdapter(adapter);
}
}
When I try to load the page in which I want to see my spinner, my application crash... I tried it into debug mod but no exception appeared.
Does somebody know what is wrong or how can I resolve my problem please?
I have the following SQL queries in my dbHelper class:
public ArrayList getAllStudents()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+ TABLE_STUDENTS, null );
res.moveToFirst();
while(res.isAfterLast() == false)
{
array_list.add(res.getString(res.getColumnIndex(ST_SURNAME)) + " , " + res.getString(res.getColumnIndex(ST_FIRST_NAME))); //+ ", " +ST_FIRST_NAME )));
res.moveToNext();
}
return array_list;
}
public ArrayList getAllStudentIds()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+ TABLE_STUDENTS, null );
res.moveToFirst();
while(res.isAfterLast() == false)
{
array_list.add(res.getString(res.getColumnIndex(ST_ID)));
res.moveToNext();
}
return array_list;
}
One is returning the student name and surname for display in a listView while the other is accessing and returning the ID of that student so that when the user clicks on a link, it directs them to the correct student profile.
I know that the best way to do this is to use a custom adapter, but i couldn't get it to work, and do not have time to give the code an overhaul (As i have a demonstration to give on this project in 30hours time)
I have the following in my studentList class:
ArrayList array_list = mydb.getAllStudents();
Log.d("array size:,", String.valueOf(array_list.size()));
final ArrayList id_list = mydb.getAllStudentIds();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_layout, array_list);
//Adding the contacts to the list view.
student = (ListView) findViewById(R.id.listView1);
student.setAdapter(arrayAdapter);
//Setting an onClickListener to process the user's actions
student.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int id_To_Search = Integer.valueOf((String)id_list.get(arg2));
Bundle dataBundle = new Bundle();
dataBundle.putInt("studentId", id_To_Search);
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.StudentProfilePage.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
I was trying to sort the list using:
Collections.sort(array_list);
And it does exactly what i need it to do - returns the student names in alphabetical order
But i need a way to link the ID that is attached to that student profile.
What is the best way to achieve this?
Thanks
Remove public ArrayList getAllStudentIds() method from dbHelper Class (Not required) and change your public ArrayList getAllStudents() like,
public HashMap<String, String> getAllStudents()
{
Map<String, String> mapStudent = new HashMap<String, String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from "+ TABLE_STUDENTS, null );
res.moveToFirst();
while(res.isAfterLast() == false)
{
mapStudent.put(res.getString(res.getColumnIndex(ST_ID)) ,res.getString(res.getColumnIndex(ST_SURNAME)) + " , " + res.getString(res.getColumnIndex(ST_FIRST_NAME))); //+ ", " +ST_FIRST_NAME )));
res.moveToNext();
}
return mapStudent;
}
So now method will return a HashMap with Student Id as Key and Student name as Value.
Now your code in StudentList class, looks like,
HashMap<String, String> studentMap = mydb.getAllStudents();
// Converting HashMap values into ArrayList
List<String> array_list = new ArrayList<String>(studentMap.values());
Log.d("array size:,", String.valueOf(array_list.size()));
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_layout, array_list);
//Adding the contacts to the list view.
student = (ListView) findViewById(R.id.listView1);
student.setAdapter(arrayAdapter);
//Setting an onClickListener to process the user's actions
student.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("arg2 ", String.valueOf(arg2));
TextView tempTextView = (TextView) arg1;
String data = tempTetxtView.getText();
for (Entry<String, String> entry : studentNameAndId.entrySet()) {
if (entry.getValue().equals(data)) {
int id_To_Search = Integer.valueOf(entry.getKey());
//id_list.get(arg2+1);
Bundle dataBundle = new Bundle();
dataBundle.putInt("studentId", id_To_Search);
//Create a new intent to open the DisplayContact activity
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.StudentProfilePage.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
}
}
});
Before you sort your names, loop through the two lists together and put the name as the key in a HashMap, with the id as the value. Then you can find the ID from the Name. Order your two SQL statements by the same columns to make sure the two lists represent students in the same order.
But of course if you have two students with the same name, you won't be able to distinguish. Really having one method connecting to the database (since you already do SELECT *) returning BOTH the ID and the name would be much better. I'd encourage you to do that, your code will be much cleaner and bug-free.
If you only need to sort the data once (or once per database access), use the database to sort your data. Something like SELECT * FROM students s ORDER BY s.student_last_name would do the trick.
But, you also have some other areas that need work. Create a Student class with, for example, firstName, lastName, and id fields. Instead of managing multiple lists, just have one List<Student>, with each Student object containing the student's name and id.
You can have the database sort them for you, or you can set up Students for Java sorting. Add implements Comparable<Student> to your Student class, and implement public int compareTo(Student s) { ... }. compareTo() should return a negative number if this comes before s, a positive number if s comes before this, or 0 if they are the same. I'd implement it like this:
public int compareTo(Student s) {
int result = this.lastName.compareTo(s.lastName);
if (result == 0) {
result = this.firstName.compareTo(s.firstName);
}
if (result == 0) {
result = this.id - s.id;
}
return result;
}
This would sort by last name, then first name, then id (and it takes advantage of String's existing compareTo(String) implementation to save yourself a lot of work).
I am using a simply city SuggestBox where I am getting list of cities from the database and putting them in GWT suggestBox oracle.
After that user can select his city from the suggestBox suggestions and user saves his record. For example, he will select "London" from the suggestbox list.
Now when user saves his record, I will not save "London" in the database for that user, instead I want to save "3" (london ID) in database.
For this what I am doing is like this:
public MultiWordSuggestOracle createCitiesOracle(ArrayList<City> cities){
for(int i=0; i<cities.size(); i++){
oracle.add(cities.get(i).getCity()+","+cities.get(i).getCityId());
}
return oracle;
}
Now, I have the city and cityID both displaying in suggestBox and then can save from there 'city' and 'cityId'.
Everything works fine, but it doesn't looks good:
like it dispays as "London,3" and so on in the suggestBox suggestions..
I don't want to show this 3, how and where can I save this Id(3) for future use?
You can also create your own typed Suggestion-Box. You need to implement "Suggestion" and extend "SuggestOracle".
Super simple version may look:
// CityOracle
public class CityOracle extends SuggestOracle {
Collection<CitySuggestion> collection;
public CityOracle(Collection<CitySuggestion> collection) {
this.collection = collection;
}
#Override
public void requestSuggestions(Request request, Callback callback) {
final Response response = new Response();
response.setSuggestions(collection);
callback.onSuggestionsReady(request, response);
}
}
//CitySuggestion
public class CitySuggestion implements Suggestion, Serializable, IsSerializable {
City value;
public CitySuggestion(City value) {
this.value = value;
}
#Override
public String getDisplayString() {
return value.getName();
}
#Override
public String getReplacementString() {
return value.getName();
}
public City getCity() {
return value;
}
}
// Usage in your code:
// list of cities - you may take it from the server
List<City> cities = new ArrayList<City>();
cities.add(new City(1l, "London"));
cities.add(new City(2l, "Berlin"));
cities.add(new City(3l, "Cracow"));
// revert cities into city-suggestions
Collection<CitySuggestion> citySuggestions = new ArrayList<CitySuggestion>();
for (City city : cities) {
citySuggestions.add(new CitySuggestion(city));
}
//initialize city-oracle
CityOracle oracle = new CityOracle(citySuggestions);
// create suggestbox providing city-oracle
SuggestBox citySuggest = new SuggestBox(oracle);
// now when selecting an element from the list, the CitySuggest object will be returned. This object contains not only a string value but also represents selected city
citySuggest.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
Suggestion selectedItem = event.getSelectedItem();
//cast returned suggestion
CitySuggestion selectedCitySuggestion = (CitySuggestion) selectedItem;
City city = selectedCitySuggestion.getCity();
Long id = city.getId();
}
});
Keep the reference from city name to id in a Map<String, Integer> and then look the ID up there before you save it.
Currently I am able to populate my spinner two ways one way gives me results from the database which is what I need but the text in the spinner is in JSON format, it all works but it looks bad, then if I extract the name from the JSON and use it I lose the value part of the name value pair.
I’ve been informed that I need to use a BaseAdapter subclass to be able to do what I need to do. The code below works just like I would love it to but the data is hard coded in, which is no use.
What I want to do is fill MyData below with the JSON data returned from the database.
This code:
final MyData items[] = new MyData[4];
items[0] = new MyData( "Ken's Plimbing","125738468");
items[1] = new MyData( "Peninsula Pests","3787906453");
items[2] = new MyData( "Joe's Electrical","129754354");
items[3] = new MyData( "Garderning Supplies","097803452");*/
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(PropertyManagement.this, android.R.layout.simple_spinner_item, items );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MyData d = items[position];
Toast.makeText(PropertyManagement.this, d.getValue(), Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
With this BaseAdapter:
class MyData {
public MyData( String spinnerText, String value ) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public String getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
String value;
Works!
But I need to fill MyData with the JSON array returned from the database. I have been doing that with the following as per the first paragraph in this post.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PropertyManagement.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final MyData items[] = new MyData[4];
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getJSONObject(i).getString("BusinessName"));
};
userSpinner.setAdapter(adapter);
The JSONArray/string looks like this,
{"BusinessName":"Petes Plumbing","BusinessPhone":"0434943743"},{"BusinessName":"Joes Electrical","BusinessPhone":"0466367279"}
Any help would be greatly appreciated.
Cheers,
Mike.
You are super close here, instead of adapter.add in your for loop you need to add it to items. Refactor like this:
final MyData items[] = new MyData[myUsers.length()];
for (int i = 0; i < MyData.length(); ++i){
items[i] = new MyData(myUsers.getJSONObject(i).getString("BusinessName"), myUsers.getJSONObject(i).getString("BusinessPhone"));
}
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(PropertyManagement.this, android.R.layout.simple_spinner_item, items );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userSpinner.setAdapter(adapter);
What is different here is your finding the length of your JSONArray, creating a new array of MyItem of that size. Then you initialize the items with new MyItems based on values from your JSONArray. Finally, you are creating the adapter with items just like you did in the first example. I'm assuming in this example that myUsers in a JSONArray.