How to extract String using AutoCompleteTextView? - java

I know that there are multiple posts in Stackoverflow addressing this query. However, for some reason I am still failing to extract the string from AutoCompleteTextView. I tried using the onItemClickListener for this purpose. I am unable to identify where I am going wrong.
The Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
addPurchaseItemName = (AutoCompleteTextView) findViewById(R.id.addPurchaseProductName);
vivzHelper = new VivzDatabaseAdapter(this);
String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
addPurchaseItemName.setThreshold(1);// starts working from first char
addPurchaseItemName.setAdapter(NameAdapter);
addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
itemName = String.valueOf(arg0.getItemAtPosition(arg2));
}
});
}
I want to assign the value of the extracted string to itemName which is initialized at the beginning of the activity. Can some one point out where am I going wrong? I have surfed multiple resources. Maybe, I am missing something.
Note :
This code was already posted to address a an issue on IllegalArgumentException in StackOverFlow a couple of days ago. Since, the topic of that question doesn't point more specifically the problem posted here, I thought that posting a new question will make sense. Hence I hope, my question won't be down-voted or edited as duplicate
Update 01 : #Deividi Cavarzan forgot including the below line of code when editing this question
ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
Update 02 : Declaring the itemName
public class AddPurchase extends ActionBarActivity {
AutoCompleteTextView addPurchaseItemName;
String itemName;

try to get the itemName on addTextChangedListener callback
addPurchaseItemName.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
itemName = s.toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});

if you just want to get the selected item string from auto complete, then
itemName = addPurchaseItemName.getText();
or even better-
itemName = addPurchaseItemName.getText().toString().trim();
Updated answer
instead of setting onItemClickListener , set OnItemSelectedListener , this should definitely work.
addPurchaseItemName.setOnSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
itemName = addPurchaseItemName.getText().toString().trim();
Toast.makeText(getApplicationContext(), "selected value - "+itemName, Toast.LENGTH_SHORT);
}
});

Related

Getting EditableText from EditText in RecyclerView

I've recycler view with 0 items, I've added an option to manually add the items, my stracture is simple :
RV_Item.xml (contains EditText).
MyItem, which is an Object for RV ( contains private String Text; ).
MainActivity.java, where the stuff happen.
// My List<Object>
List<MyItem> Items = new ArrayList<>();
// For Adding, I've added FAB-Button, When Clicked, it does the following :
Items.add(new MyItem());
CheckForEmptyItems();
mAdapter.notifyItemInserted(0);
Now, When the user click the save button, i want to take all the edittext in all the items he had added, i'm doing in the following way :
for(MyItem items : Items){
Log.i("PrintingInfo", items.getText() );
}
The problem is, i'm not getting the text he entered in all EditText fields, and it's returning Null in all of them, What's the issue in this ?
So, i don't know why always i know the answer after posting, but here's how you gonna know what the user typed :
in your Adapter Class, in onBindViewHolder method, add textlistener for the EditText, here's an example :
holder.MyEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
itemList.get(position).setText(s.toString());
}
});
Hope that helps you!

Passing an _id from one activity to another when ListView item is clicked

I have a problem. In my activity i have a ListView whose values are compiled from a Database. The database returns three columns: _Id, AccountName and Comments. What i want is that the when the user clicks on one of the items in the listView, that Item's position will be extracted and then that position will be compared with the postion in the ArrayList which has the data and then when the specific field and row is found out, the _Id field will be taken out and passed to another activity in the form of a String.
You may not have understood much; this might help:
public void search(View view){
final ListView vLst_IDCommName=(ListView)findViewById(R.id.lst_IDCommName);
EditText vTxt_searchTxt=(EditText)findViewById(R.id.search_txt);
String srch_str= vTxt_searchTxt.getText().toString();
if(srch_str.length()>0){
//The DataSource for the LstView
List<Comment> values = datasource.getContacts(srch_str);
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
vLst_IDCommName.setAdapter(adapter);
}
else{
Toast.makeText(getBaseContext(), "Please type in a value to proceed!", Toast.LENGTH_LONG).show();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Here I want to create a function that will take the position of the item clicked
//and then searched for that position in the ArrayList and then return the _Id of
//the account whose value was clicked.
}});
}
This code I used to get data:
public List<Comment> getContacts(String search_str) {
List<Comment> comments = new ArrayList<Comment>();
String srch_str=(String) search_str;
Cursor cur_comments= database.rawQuery("Select * from comments where acc_name like('%"+srch_str+"%')"+" "+ "or comment like('%"+srch_str+"%')", null);
cur_comments.moveToFirst();
while (!cur_comments.isAfterLast()) {
Comment comment = cursorToComment(cur_comments);
comments.add(comment); cur_comments.moveToNext();
}
cur_comments.close();
return comments;
}
Any feedback would be appreciated.
you can try
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String currentId=yourArrayList.get(position).toString();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Object s=parent.getItemAtPosition(position);
String j=s.toString();
}});

Perform click event on Spinner to execute code in onItemSelected

I want to perform a click on a Spinner element automatically after my activity has been loaded completely.
I use this code to set up the spinner and adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_data);
getActionBar().setDisplayHomeAsUpEnabled(true);
mSpinnerDay = (Spinner) mTable.findViewById(R.id.spieltag_choice);
mAdapterSpinnerDay = new ArrayAdapter<CharSequence>(this, R.layout.custom_spinner);
mAdapterSpinnerDay.setDropDownViewResource(R.layout.custom_spinner);
mSpinnerDay.setAdapter(mAdapterSpinnerDay);
}
private void setUpSpinnerListener(final IGameData data) {
mSpinnerDay.post(new Runnable() {
public void run() {
mSpinnerDay.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
for (GameDayData d : data.getGameDay()) {
if (d.getName().equals(adapterView.getSelectedItem().toString())) {
TableRow row = (TableRow) mTable.findViewById(R.id.row_punkte_tag);
TextView t = (TextView) row.findViewById(R.id.punkte_tag);
t.setText("Punkte: " + d.getScore());
TableRow row2 = (TableRow) mTable.findViewById(R.id.row_position_tag);
TextView t2 = (TextView) row2.findViewById(R.id.position_tag);
t2.setText("Position: " + d.getPosition());
return;
}
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
}
});
}
public void onTeamCheckReadComplete(IGameData data) {
for (GameDayData d : data.getGameDay()) {
mAdapterSpinnerDay.add(d.getName());
}
}
I try to perform the click with following code after I have set the adapter to the spinner:
mSpinnerDay.setSelection(0, true);
View view = (View) mSpinnerDay.getChildAt(0);
long id = mSpinnerDay.getAdapter().getItemId(0);
mSpinnerDay.performItemClick(view, 0, id);
But this does not work. Could somebody tell me how I can perfom a click on a spinner element automatically? When I select the spinner item over touch event in the application everything works fine.
Regards,
Sandro
Corrected Solution
As I understand it, you have a spinner with items A, B, C, and D. You want item A pre-selected. You also want the user to be able to select A, B, C, and D and perform an action based on that.
In the onCreate() method:
mSpinner.setAdapter(myAdapter);
mSpinner.setOnItemSelectedListener(this); // have the activity implement
// OnItemSelectedListener interface
doAction(0);
Then implement the onItemSelected action like so:
#Override
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
doAction(position);
}
You must implement the doAction(int position) method to handle how to update your activity based on the position of the item in your adapter. Clear?
Read more about this item and how to use it here:
http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
I dont think you are calling setUpSpinnerListener from the code that you have posted. Even if you are calling it, i dont think it is advantageous to post a runnable to setuplistener.
Move all the code in runnable to just after setAdapter

Pass String variables by reference to setOnItemSelectedListener of multiple Spinners

OK, I've read around and see that Java only passes by value, not by reference so I don't know how to accomplish this.
I've 6 Spinners in an Android Activity that are populated with different SQLite queries.
The code to populate each Spinner and set the OnItemSelectedListener is very similiar so I was hoping to refactor to one method and call it 6 times with each Spinner ID and Sqlite query.
How do I get the Spinner onItemSelectedListener to change the right instance member on each different Spinner?
public void fillSpinner(String spinner_name, final String field_name) {
// This finds the Spinner ID passed into the method with spinner_name
// from the Resources file. e.g. spinner1
int resID = getResources().getIdentifier(spinner_name, "id",
getPackageName());
Spinner s = (Spinner) findViewById(resID);
final Cursor cMonth;
// This gets the data to populate the spinner, e.g. if field_name was
// strength = SELECT _id, strength FROM cigars GROUP BY strength
cMonth = dbHelper.fetchSpinnerFilters(field_name);
startManagingCursor(cMonth);
String[] from = new String[] { field_name };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter months = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cMonth, from, to);
months.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(months);
// This is setting the Spinner Item Selected Listener Callback, where
// all the problems happen
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
// This is the problem area.
object_reference_to_clas_member_of_field_name = theCursor
.getString(theCursor.getColumnIndex(field_name));
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner1: unselected");
}
});
}
You call this method like this fillSpinner("spinner1","strength");.
It finds the spinner with id spinner1 and queries the database for the strength field. field_name, which is strength in this example had to be declared a final variable to be used in the onItemSelectedListener or I'd get the error Cannot refer to a non-final variable field_name inside an inner class defined in a different method.
But how do I get the onItemSelectedListener to change the value of a different instance member when each different Spinner is used? This is the all important line of code:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
I can't use a final String as the variable will obviously change when the user selects a different value. I've read around a good bit and am stumped to a solution. I can just copy and paste this code 6 times and forget about refactoring but I'd really like to know the elegant solution. Post a comment if you don't understand my question, I'm not sure if I explaned myself well.
You can do it, by passing additional class as parameter of fillSpinner method:
A. Create interface
public interface OnSpinnerValueSelected {
void onValueSelected(String selectedValue);
}
B. Change your method a bit:
public void fillSpinner(String spinner_name, final String field_name,
final OnSpinnerValueSelected valueChangeListener) {
// Prepare spinner
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
valueChangeListener.onValueSelected(theCursor
.getString(theCursor.getColumnIndex(field_name)));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
C. provide listener:
fillSpinner("spinner1","strength", new OnSpinnerValueSelected() {
public void onValueSelected(String selectedValue) {
yourObject.setField(selectedValue);
}
});
Refactor your listener to a new "class". Initialize with the right arguments/instances as required so that the repeated "code" is reusuable.
Right, this is how I managed it but I'm still open to new suggestions for an accepted answer and I also created a bounty.
I didn't create a new class like panzerschreck suggested so I'm posting this as a new answer to my own question. Bit of a hack but I just created an if..then..else statement in the listener to check what spinner was selected and then set a different instance member.
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
if (field_name.equalsIgnoreCase("strength")) {
strength=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("ring")) {
ring_gauge=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("country")) {
country=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("wrapper")) {
wrapper=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("length")) {
length=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("price")) {
price=theCursor.getString(theCursor.getColumnIndex(field_name));
}
// showToast(category);
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner2: unselected");
}
});
Here are the class members
private String strength,ring_gauge,country,wrapper,length,price;
Bit of hack but without Java allowing objects to be really passed by reference, it's all I could do.

Searching partial word in a arraylist on android

Im having a lot of problems with searching for part of a word, and then making it find the full result afterwards.
Like if im searching "droid", it looks through my list for anything that contains "droid", if you look at my arraylist underneath it should find "Android"
Arraylist code:
private List<String> getModel() {
List<String> list = new ArrayList<String>();
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
return list;
}
Here's the rest of my code:
public class idchart extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.idchart);
/*Resources res = getResources();
ListView listView=(ListView)findViewById(R.id.list);*/
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.srcBox);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
As suggested, using Regex, as far I know you would have to iterate the list and try to match every entry.
If you want to avoid iteration, you can use a inverted index approach for each character (like NGram) of the word. If you want to search text starting with what the user sends, you can do it with Java Map (Commons MultiMap). If you want to search by "droid", so you would have to index the position of each character and retrieve the relative results. I don't recommend doing that without a Library like Lucene.

Categories

Resources