here i have an array list
ArrayList<String> arrlist = new ArrayList<String>();
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autocompletetextview.setAdapter(adapter1);
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
prepareMyList();
}
private void prepareMyList() {
ArrayList<String> arrlist = new ArrayList<String>();
String selectQuerys = "select distinct location from tb_user where location like '%"+autoservice.getText().toString()+"%'";
SQLiteDatabase dbs = sq.getReadableDatabase();
Cursor cursors = dbs.rawQuery(selectQuerys, null);
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autoservice.setAdapter(adapter1);
}
}
#Override
public void afterTextChanged(Editable s) {
}
if i type 'a' in autocomplete textview all items stating with 'a' will come as suggestions, similarly for all other letters
my need is i need a default item "automatic" at first of suggestion eventhough we type any letter in autocomplete textview
It sounds like you need to add the automatically detected location before you loop through the cursor. Earlier on, I'm assuming in onCreate, it would be:
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("automatically detect");
while (cursors.moveToNext()) { //...
Then in prepareMyList:
private void prepareMyList() {
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("automatically detect");
String selectQuerys = //...
This should add "automatically detect" as the first item initially and when you search.
Note: You should consider moving some of your code out of your while loop to make it more efficient (and likely less buggy). You don't need to create a new ArrayAdapter or set the adapter every time through the loop. You can just do this one time after the loop ends. All you need in your loops is:
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
}
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autoservice.setAdapter(adapter1);
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("Default element");
Related
I have an edittext field in a tab which is given a unique autogenerated value when the activity is created. I want this value passed to a static class as soon as the value is put in the edittext so that on switching tabs, the value can be called from the static class.
My problem is i tried saving the value to the static class using the following code:
invoiceNo.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//GlobalApp.data().id = invoiceNo.getText().toString();
}
public void beforeTextChanged(CharSequence s, int a, int b, int c){
GlobalApp.data().id = invoiceNo.getText().toString();
}
public void onTextChanged(CharSequence s, int a, int b, int c){
// GlobalApp.data().id = invoiceNo.getText().toString();
}
}
But it kept changing whenever the user returns to the 1st tab (where the value is generated) or it would not be displayed at all. I want it to save the generated value once irrespective of whether user returns to the 1st Tab.
public class clientFragmentTab extends Fragment {
ArrayList<String> saleRecord;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
EditText currDate, invoiceNo , vehicle,territory ;
//Spinner clientName, territory;
View rootView = null;
int invoice_id = 0;
String invoice_no;
public String[] item = new String[] {"Please search..."};
public String territory1;
CustomAutoCompleteView myAutoComplete;
ProductsDbHelper db;
// adapter for auto-complete
ArrayAdapter<String> myAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.client_layout, container, false);
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
myAutoComplete = (CustomAutoCompleteView) rootView.findViewById(R.id.myautocomplete);
// add the listener so it will tries to suggest while the user types
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this, getActivity()));
db = new ProductsDbHelper(getActivity());
// set our adapter
myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, item);
myAutoComplete.setAdapter(myAdapter);
currDate = (EditText) rootView.findViewById(R.id.editText4);
//clientName = (Spinner) rootView.findViewById(R.id.spinner);
invoiceNo = (EditText) rootView.findViewById(R.id.editText3);
vehicle = (EditText) rootView.findViewById(R.id.editText6);
territory = (EditText) rootView.findViewById(R.id.editText9);invoice_id = UniqueRandomNumbers();
invoice_no = "invoice_" + invoice_id;
currDate.setText(formattedDate);
invoiceNo.setText(invoice_no);
//List<String> list = new ArrayList<String>();
//list.add("Select Client");
//list.add("Item 2");
//list.add("Item 3");
//list.add("Item 4");
//list.add("Item 5");
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item , list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//clientName.setAdapter(adapter);
// if(invoiceNo.getText().toString() != ""){
// }
invoiceNo.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//GlobalApp.data().id = invoiceNo.getText().toString();
}
public void beforeTextChanged(CharSequence s, int a, int b, int c){
GlobalApp.data().id = invoiceNo.getText().toString();
}
public void onTextChanged(CharSequence s, int a, int b, int c){
// GlobalApp.data().id = invoiceNo.getText().toString();
}
}
);
}
You seem to be approaching this all wrong, when something feels like you're having to force it it usually signals a problem with the project architecture. The solution should be something like the following:
1. onCreate generate that id and store it in a *member variable*, lets call it mInvoiceId
2. onCreateView or onViewCreated do invoiceNo.setText(mInvoiceId)
3. if it's still required, in onTextChanged do mInvoiceId = s; (the 's' param should be the same result as invoiceNo.getText().toString() I believe)
4. if you're really set on using a static class you can replace any use of mInvoiceId with GlobalApp.data().id but static classes are usually bad.
- You can pass things between fragments correctly using saveInstanceState or intents with extras (not sure what you want to do)
I hope that sets you in the right direction
I am new to android i am using the search in my android using edittext search is working fine and code of search is as follow:
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
// When user changed the Text
arrayAdapter.getFilter().filter(s);
arrayAdapter.notifyDataSetChanged();
}
..........
}}
I am using simpleadapter to display the data in listview having two colomn col1,col2
say:
arrayAdapter = new SimpleAdapter(LabelUser.this, mylistData,
R.layout.two_col_row, columnTags, columnIds);
list.setAdapter(arrayAdapter);
on click of list:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
// TODO Auto-generated method stub
String selectedFromList = (list.getItemAtPosition(position).toString());
System.out.println(selectedFromList);
startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
}
});
And gives output as:
{col1=A K JOHN, col2=21.45}
My Question is how to get a string from above i.e. of col1
example var = "A K JOHN"
listview creation:
final ListView list = (ListView) findViewById(R.id.listView1);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] { "col1", "col2" };
int[] columnIds = new int[] { R.id.column1, R.id.column2 };
for (int i = 0; i < labelIdArray.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("col1", labelArray[i]);
map.put("col2", labelRateArray[i]);
mylistData.add(map);
list.setAdapter(arrayAdapter);
}
If you want to fetch the value of first Column, I think the following code will work,
String selectedFromList = columnTags[position];
Just give it try and tell if it worked or not.
I'm creating an activity wherein there are textview/autocompletetextview, listview and a button. My autocompletetextview works well, but I want to index what I input in the textview to the listview and when the it is highlighted, I'd click the button and go to the corresponding activity.
Here's so far what I've done:
String[] classes = {
"Acornsquash",
"Almonds",
"Apples", }
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature( Window.FEATURE_LEFT_ICON );
setContentView(R.layout.nutritional_list);
setFeatureDrawableResource( Window.FEATURE_LEFT_ICON, R.drawable.nutrition32 );
//ArrayAdapter<String> adapter = new ArrayAdapter<String>( this,
// android.R.layout.simple_dropdown_item_1line, classes );
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classes );
AutoCompleteTextView tv = ( AutoCompleteTextView ) findViewById ( R.id.txtSearcEngine );
tv.setThreshold( 3 );
tv.setAdapter( adapter );
tv.setTextColor( Color.BLACK );
lv = ( ListView ) findViewById(R.id.lvListSearch);
lv.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes ) );
lv.setOnItemClickListener( this );
public void onItemClick( AdapterView<?> parent, View v, int position, long id ) {
lv.setSelection(position);
switch( position )
{
case 0:
Intent acorn = new Intent( Nutritional_List.this, AcornSquash.class );
startActivity( acorn );
break;
case 1:
Intent almonds = new Intent( Nutritional_List.this, Almonds.class );
startActivity( almonds );
break;
My problem is, I don't have a clue on how to index suggestion from autocompletetextview to listview. Any help? thanks.
Rewrite
I am posting two ways to accomplish what you want. I believe that first method is simpler to code and less confusing to use. The second method is the direct answer to your question.
Method 1
I find it curious that you are using an AutoCompleteTextView and a ListView when they both provide the same information. The AutoCompleteTextView has the advantage of filtering the selection based on the user's text, but you can remove the AutoCompleteTextView and Button by using adding simple EditText that filters the ListView itself.
EditText edit = (EditText) findViewById(R.id.edit);
edit.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
Where adapter is a class variable like lv, tv, etc. and is the adapter passed to lv:
adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes );
lv.setAdapter(adapter);
Method 2
To do what you asked about initially, first let's change classes to a more powerful ArrayList<String>:
ArrayList<String> classesList = new ArrayList<String>(Arrays.asList(classes));
...
public void onCreate() {
...
// Update both of your adapters!
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classesList );
create a new class variable as int tvIndex = -1. We'll use it when we click an item from the AutoCompleteTextView:
tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = ((TextView) v).getText().toString();
tvIndex = classesList.indexOf(text);
lv.setSelection(tvIndex);
}
});
If the user pushes the Button to proceed:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tvIndex > -1)
lv.performItemClick(lv.getChildAt(tvIndex), tvIndex, tvIndex);
}
});
Hope that helps!
I have a long list of data display in android spinner. So i want to add a search option to this spinner ? Can any one help me with a simple example code.. (I saw some answers regarding this but they are not sufficient)..
I am new to android and i know actually this is not the correct way. but i want to add this kind of option to the spinner. When you hit a letter on the search box , list of items are displayed in the spinner relevant to that letter. Thanks a lot.
public void search(View view){
cursor = db.rawQuery("SELECT * FROM tblRepTeritories WHERE RepCode like?",
new String[]{"%" + searchText.getText().toString() + "%"});
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
cursor,
new String[] {"TeriCode"},
new int[] {android.R.id.text1});
adapter1.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
Spinner s1 = (Spinner) findViewById( R.id.spinner2 );
s1.setAdapter(adapter1);
}
Use TextWatcher and then call notifyDataSetChanged() on your adapter:
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
cursor = db.rawQuery("SELECT * FROM tblRepTeritories WHERE RepCode like?",
new String[] {"%" + searchText.getText().toString() + "%"});
adapter1.notifyDataSetChanged();
}
});
OK, I am working on an App that has a page with a listview and a edittext box at top. As you type things into the edittext box it will filter what items are shown in the listview. The problem I am having is with the fast scroll icon that appears on the side of the slider.
When the page first loads NO MATTER what I do the fast scroll slider icon will not appear on the screen. Then I click in the edit text box and type one character and then erase it and now my fast scroll slider icon will appear.
First load no fast scroll icon.
Edittext box and then erase text and fast scroll icon appears.
I have the android:fastScrollEnabled="true" set in my listview. Plus I have set it manually in the code by doing lv1.setFastScrollEnabled(true);
No matter I change I still get the same behavior, unless I remove it complete from the code and xml and then it will stop working on the second page. I have tried cleaning my project and still no good. I am leaning towards it being a bug in android or I am missing something extremely simple.
Here is my code.
public class SearchByFood extends ParentClass
{
private ListView lv1;
private EditText ed;
int textlength = 0;
private ArrayList<String> arr_sort = new ArrayList<String>();
private ArrayList<String> foods = new ArrayList<String>();
private LayoutInflater mInflater;
private ArrayList<Food> foodList;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_by_food);
setTextTitle("Search by Food");
lv1 = (ListView) findViewById(R.id.ListView01);
ed = (EditText) findViewById(R.id.EditText01);
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DataLayerFunctions d = new DataLayerFunctions(getApplicationContext());
foodList = d.selectFoodsWithSubstitutes();
for (Food f : foodList)
{
// this is to build a ArrayList<String> to pass to the setAdapter
Log.d("SearchByFood", "FoodName: " + f.getFood_Name());
foods.add(f.getFood_Name());
}
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(SearchByFood.this, R.layout.search_food_listview, foods);
lv1.setAdapter(firstAdapter);
lv1.setFastScrollEnabled(true);
ed.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
textlength = ed.getText().length();
arr_sort.clear();
for (String f : foods)
{
if (textlength <= f.length())
{
if (f.toString().toLowerCase().contains((CharSequence) ed.getText().toString().toLowerCase()))
{
Log.d("STRING", "STRING: " + f.toString() + " contains " + ed.getText());
if (ed.getText().length() > 0)
{
String newString = boldMyString(f, ed.getText().toString());
arr_sort.add(newString);
}
else
{
arr_sort.add(f);
}
}
}
}
// if empty add a no foods found
if (arr_sort.isEmpty())
{
arr_sort.add("No Foods Found");
}
// Load array
// lv1.setAdapter(new
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchByFood.this, R.layout.search_food_listview, arr_sort)
{
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
if (null == convertView)
{
row = mInflater.inflate(R.layout.search_food_listview, null);
}
else
{
row = convertView;
}
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(Html.fromHtml(getItem(position)));
// tv.setText(getItem(position));
return row;
}
};
lv1.setAdapter(adapter);
}
private String boldMyString(String foodName, String guess)
{
int gLength = guess.length();
ArrayList<Integer> results = new ArrayList<Integer>();
for (int i = foodName.toLowerCase().indexOf(guess.toLowerCase()); i >= 0; i = foodName.toLowerCase()
.indexOf(guess.toLowerCase(), i + 1))
{
System.out.println("TEST:" + i);
results.add(i);
}
// Count value is for words that have 2 or more values of guess
// in them.
int count = 0;
for (int i : results)
{
StringBuffer s1 = new StringBuffer(foodName);
s1.insert(i + count, "<b>");
count = count + 3;
s1.insert(i + count + gLength, "</b>");
count = count + 4;
foodName = s1.toString();
System.out.println("FOOD NAME:" + i + ":" + foodName);
}
return foodName;
}
});
// This is what actually does stuff when you click on a listview item.
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Strip out the bold tags
String clicked = (String) lv1.getItemAtPosition(position);
clicked = clicked.replaceAll("<b>", "");
System.out.println("Clicked" + clicked);
clicked = clicked.replaceAll("</b>", "");
// Find the Food ID match and pass the food id to the
// fooddisplay page
for (Food f : foodList)
{
if (null != clicked && clicked.equals(f.getFood_Name()))
{
Intent intent = new Intent(SearchByFood.this, SubstituteDisplay.class);
intent.putExtra("FoodID", f.getFood_ID());
startActivity(intent);
}
}
}
});
}
#Override
public void onBackPressed()
{
final Intent intent = new Intent(this, MasterTemplateActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
return;
}
}
Again, any help as to why my fast scroll icon doesn't show up at first would be much appreciated. It is a small thing but it is really annoying me.
try list.setFastScrollAlwaysVisible(true)
and also try list.smoothScrollToPosition(0); so that icon appears when scroll is called...
something like this..
new Handler().postDelayed(new Runnable() {
#Override
public void run(){
list.smoothScrollToPosition(0);
}
}, 100);
So again I'm posting this because my issue was genuinly different. Fast scrolling also doesn't seem to work in a ConstraintLayout. Both ListView Fast Scrolling and RecyclerView Fast Scrolling don't seem to work.