Searching partial word in a arraylist on android - java

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.

Related

autoCompleteTextView shows results only after deleting a letter

I created a layout that has an autoCompleteTextView in it that should show some names of books.
I noticed that it show no results in some cases unless I delete one letter and then it shows the correct results.
For example, I have an array string of books that has the word Potter in them.
When I type Potter, it shows no results:
However, if I then delete one letter it suddenly shows:
The code im using to populate the list is:
atv_Search.addTextChangedListener( new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
SOME CODE TO GET NAMES
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
Set<String> set = new LinkedHashSet<>( autoBookNames );
autoBookNames.clear();
autoBookNames.addAll( set );
// UNTIL THIS POINT IT ALL WORKS GOOD AND I SEE THAT authBookNames IS NOT EMPTY, YET NOT SHOWING UNTIL DELETE
listAutoAdapter = new ArrayAdapter<String>( getApplicationContext(), R.layout.item_auto_search, autoBookNames );
atv_Search.setThreshold( 1 );
atv_Search.setAdapter( listAutoAdapter );
}
} );
As I wrote in the code when I debugged it, I did get all the results even before the deletion but it didn't show it for some reason.
Any reason for this? I mean most users won't think to delete a letter to show the results.
Thank you
try==>
listAutoAdapter = new ArrayAdapter<String>( getApplicationContext(), R.layout.item_auto_search, autoBookNames );
atv_Search.setAdapter( listAutoAdapter );
atv_Search.addTextChangedListener( new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
listAutoAdapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
} );
let me know if this works
Do you think that your compare strings' index in "SOME CODE TO GET NAMES" is wrong (such as last index is smaller than the correct one 1 character)
Move
listAutoAdapter = new ArrayAdapter<String>( getApplicationContext(), R.layout.item_auto_search, autoBookNames );
atv_Search.setThreshold( 1 );
atv_Search.setAdapter( listAutoAdapter );
into onTextchanged and try once, Ben!

Updating ArrayList when the data is changed in Firebase

I am using an ArrayList (in Android) that contains the values from the Firebase database. Whenever the data is added or deleted, I want the list to be updated. To do this I used ChildEventListener but I am unsure whether this is a proper way of doing it as I face errors sometimes while deleting the elements from the list. There's no problem at all when adding elements to the list. But When I try to delete the last element from the list, I get ArrayIndexOutOfBounds Exception or some other Exception like length=12 index=-1. So, please go through my code and suggest a better way to delete elements:
public class Join extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listView;
public static ArrayList<String> keysArrayList;
//To store the keys from Firebase
public static ArrayList<String> namesArrayList;
//To store the value or name associated with the key
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_join);
databaseReference = FirebaseDatabase.getInstance().getReference().child(“Queue Codes”);
listView = (ListView) findViewById(R.id.listViewForMember);
keysArrayList = new ArrayList<>();
namesArrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>
(this,android.R.layout.activity_list_item,namesArrayList);
listView.setAdapter(arrayAdapter);
/* Here I am trying to store Random keys from Firebase in
‘keysArrayList’ and their values in ‘namesArrayList’ and update these
lists whenever a value is added or removed from the database*/
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String addedKey = dataSnapshot.getKey();
String addedName = dataSnapshot.getValue(String.class);
keysArrayList.add(addedKey);
namesArrayList.add(addedName);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String removedKey = dataSnapshot.getKey();
int index = keysArrayList.indexOf(removedKey);
namesArrayList.remove(index);
keysArrayList.remove(removedKey);
arrayAdapter.notifyDataSetChanged();
/* Here I tried to remove the name from the ‘namesArrayList’ by
using the index of removed value from ‘keysArrayList’ as both
the lists would be of the same size anytime. I can simply
delete the name from the ‘namesArrayList’ by reading the
removed value from firebase but gets difficult when I use
Custom Array Lists which may contain many other objects. So, I
decided to delete the name using key index. */
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
In order to solve this problem, you need to remove that particular element first from the adapter. If you want not to worry about adding or removing elements, I recommend you see my answer from this post, in which I have explained how you can get data from the Firebase Realtime database and display it in a ListView using an ArrayAdapter.

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!

Spinner in Custom Function for Android with java

I am confused about calling the spinner widget through a custom function. I am create an app in which I use spinner 20-35 times a spinner widget in single layout or activity. So for this i want to avoid the spinner code repetition again and again. i am creating a method for this i add the items to the spinner but i want to pass item value on select to other activity which bind to that class
Here is my code
Spin_tester.class
public class Spin_tester {
public String result;
public Context ctx;
public Spin_tester(Spinner spinner, final ArrayList<String> arraylist, final Context ctx , final String value) {
this.ctx= ctx;
ArrayAdapter<String> adpts =
new ArrayAdapter<String>(ctx, android.R.layout.simple_dropdown_item_1line,arraylist);
spinner.setAdapter(adpts);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
result = arraylist.get(position);
value = result ; // This is not working
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Test_Activity.class
public class Test_Activity extends AppCompatActivity {
ArrayList<String> data_list = new ArrayList<>();
Spinner spins;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
spins = (Spinner)findViewById(R.id.spinner);
data_list.add("1");
data_list.add("2");
data_list.add("3");
data_list.add("4");
Spin_tester asd = new Spin_tester(spins,data_list,this,value);
TextView txt = (TextView)findViewById(R.id.textView17);
}
}
Please help
Thanks in advance
Java is a pass-by-value language, not pass-by-reference. What this means is that setting value in setOnItemSelectedListener will only change value within that method — the result won't be passed back anywhere.
I see that you've place the result in result. That is where the calling program will find the answer.
Remove all instances of value from Spin_tester and Test_Activity and then have your main activity get the result from asd.result
I'm going to get a little meta at this point: I've only answered the question you actually asked, but this code is wrong on so many levels that you're never going to get it to work. I strongly suggest you work your way through the examples and tutorials in the documentation before you try to proceed any further.

How to extract String using AutoCompleteTextView?

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);
}
});

Categories

Resources