0% found this document useful (0 votes)
77 views15 pages

Artificial Intelligence in Healthcare

The document describes how to add a search function to a list view in Android. It involves: 1. Adding a SearchView widget to the action bar to allow searching of list content. 2. Creating a menu resource file with a search menu item to display the SearchView. 3. Defining a SearchableConfiguration XML file to configure SearchView behavior. 4. Implementing search functionality by filtering the list adapter based on user input in the SearchView.

Uploaded by

Shivangi Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views15 pages

Artificial Intelligence in Healthcare

The document describes how to add a search function to a list view in Android. It involves: 1. Adding a SearchView widget to the action bar to allow searching of list content. 2. Creating a menu resource file with a search menu item to display the SearchView. 3. Defining a SearchableConfiguration XML file to configure SearchView behavior. 4. Implementing search functionality by filtering the list adapter based on user input in the SearchView.

Uploaded by

Shivangi Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Add search function to list view in

android
Action bar with SearchView

 Beginning with Android 3.0, android supports to add SearchView widget to your action bar.
This search view can be use to search the content in a list view

More info about SearchView


http://developer.android.com/training/search/setup.html

 Following are the implementation steps of searchable list view

Add search menu

 Create a menu resource file with search menu item(when click on search menu item, search
widget will be appear in action bar)
 Following is an example menu resource that I have created( res/menu/search_menu.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />

</menu>

 In above menu item the collapseActionView attribute allows your SearchView to expand to
take up the whole action bar and collapse back down into a normal action bar item when not
in use

Create SearchableConfiguration

 Searchable Configuration defines how SearchView behaves


 Need to define it in a xml(res/xml/searchable.xml). Following is an example searchable
configuration file
<?xml version="1.0" encoding="utf-8"?>
<searchable
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="Search friend">

</searchable>
 Then add this element into a relevant activity with <meta-data> tag

<activity
android:name=".ui.FriendListActivity"
android:screenOrientation="portrait"
android:configChanges="orientation"
android:theme="@style/Theme.Yello"
android:windowSoftInputMode="stateHidden"
android:launchMode="singleTask"
android:parentActivityName=".ui.SensorDetailsActivity">
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable">
</meta-data>

</activity>

 In my scenario I'm gonna add SearchView to FriendListActivity

Add Menu and SearchableConfiguration to activity

 Associate searchable configuration with the SearchView in the activity class

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);

SearchManager searchManager = (SearchManager)


getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();

searchView.setSearchableInfo(searchManager.
getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);

return true;

 Now the SearchView added to the activity. But still searching functionality not working
Add searching functionality

 Implement SearchView.OnQueryTextListener in activity, need to override two new methods


now

public boolean onQueryTextSubmit(String query)

public boolean onQueryTextChange(String newText)

 This interface listen to text change events in SearchView

@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
friendListAdapter.getFilter().filter(newText);

return true;

 In here onQueryTextChange function do the filtering with list adapter, In order to do the
filtering, adapter need to be implement Filterable interface
 Following is the complete implementation of list activity( FriendListActivity)
https://github.com/erangaeb/dev-notes/blob/master/android-search-list/FriendListActivity.java

Filterable adapter

 In my scenario I have used BaseAdapter with implementing Filterable interface


 Following is the implementation of my adapter class( FriendListAdapter)
https://github.com/erangaeb/dev-notes/blob/master/android-search-list/FriendListAdapter.java

 In here I have defined custom Filter class FriendFilter to do the filtering, I'm filtering the
list according to the nameentering in SearchView
 I have defined two array lists here. One for display in list view and other one for
filtering(original list)
// original list, filtering do with this list
private ArrayList<User> friendList;

// filtered list construct by filtering the friendList


// it uses to create the list view

private ArrayList<User> filteredList;

 Searching functionality is working now. Following is an example output of searching list

Collapse action bar SearchView programatically

 In my scenario when list item clicks, I'm navigate to new activity ShareActivity
 When navigating, I'm collapsing the SearchView if it is visible
private void handelListItemClick(User user) {
// close search view if its visible
if (searchView.isShown()) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}

// pass selected user and sensor to share activity


Intent intent = new Intent(this, ShareActivity.class);
intent.putExtra("com.score.senzors.pojos.User", user);
this.startActivity(intent);
this.overridePendingTransition(R.anim.right_in, R.anim.stay_in);

Add search view popup text while searching

 First enable filtering on the list view

friendListView.setTextFilterEnabled(true);

 Modify onQueryTextChange function like below

@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
friendListView.clearTextFilter();
}
else {
friendListView.setFilterText(newText.toString());
}

return true;

 Now search view popup will be visible when searching. Actually is displays text that typing
in SearchView

ANOTHER CODE (ALTERNATE METHOD)(KOTLIN)


SearchView in ListView with a custom Adapter using Kotlin
in Android

1. Creating New Project in Kotlin

 Open Android Studio.


 Go to File => New => New Project.Give Name To your application. The
n, check Include Kotlin Support and click next button.
 Select minimum SDK you need. However, we have selected 21 as minimu
m SDK. Then, click next button.
 Then, select Empty Activity => click next => click finish.
2. For Search in Custom ListView We need two XML file main xml file con
tain listView and SearchView.
Other Contain a Single ROW which we want to Show in ListView.Here we
Have Two XML file

1. main_activity.xml
2. list_row.xml
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

list_row.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/imageview"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="12dp" />

<TextView
android:id="@+id/header"
android:textSize="16sp"
android:textColor="@color/colorPrimary"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageview"
android:layout_marginStart="18dp"
android:layout_marginTop="13dp"
android:layout_toEndOf="@+id/imageview" />

<TextView
android:id="@+id/subHeader"
android:textSize="12sp"
android:textStyle="bold"
android:textColor="@android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/header"
android:layout_below="@+id/header" />

</RelativeLayout>

3. MainActivity.kt

package com.dharmendra.searchview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ListView
import android.widget.SearchView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

//Find View By Id For Listview


val listview = findViewById(R.id.listView) as ListView

//Find View By Id For SearchView


val searchView = findViewById(R.id.searchView) as SearchView

/*Create and ArrayList of Integer Type To Store Images From


drawable.Here we add Images to ArrayList.
We have Images of Android Icons of Diffrent versions.
*/
val image = ArrayList<Int>()
image.add(R.drawable.cupcake)
image.add(R.drawable.donut)
image.add(R.drawable.eclair)
image.add(R.drawable.froyo)
image.add(R.drawable.gingerbread)
image.add(R.drawable.honeycomb)
image.add(R.drawable.icecreamsandwich)
image.add(R.drawable.jellybean)
image.add(R.drawable.kitkat)
image.add(R.drawable.lollipop)
image.add(R.drawable.marshmallow)
image.add(R.drawable.nougat)
image.add(R.drawable.oreo)

// Here We take and Array of Android OS names in Same Sequence as


we take Images.

val name = arrayOf("Cupcake", "Donut", "Eclair", "Froyo",


"Gingerbread", "Honeycomb", "Icecreamsandwich",
"Jellybean", "Kitkat", "Lollipop", "Marshmallow", "Nougat",
"Oreo")

// Here We take and Array of Android OS Version in Same Sequence as


we take Images and name.

val version = arrayOf("1.5", "1.6", "2.0", "2.2", "2.3", "3.0",


"4.0",
"4.1", "4.4", "5.0", "6.0", "7.0", "8.0")

/*Create ArrayList of HashMap to Store Name and Version with Key


value Pair at Same poition

Ex:-
At Position 1:
name:"Cupcake"
version:"1.5"
At Position 2:
name:"Donut"
version:"1.6"
.
.
.
So On
*/
val info = ArrayList<HashMap<String, String>>()

//Here We take HashMap in that we add Name and Version from Array
var hashMap: HashMap<String, String> = HashMap<String, String>()

for (i in 0..name.size - 1) {
hashMap = HashMap<String, String>()
hashMap.put("name", name[i])
hashMap.put("version", version[i])

//Add HashMap to ArrayList


info.add(hashMap)

/*
ArrayList Start with Position 0

So we have At position 0:

name:"Cupcake"
version:"1.5"

*/

//We Have Created Custom Adapter Class in that we pass


Context,Array of Image and ArrayList<Hashmap<String,String>>
val customAdapter = CustomAdapter(this, image, info)

//Set Adapter to ArrayList


listview.adapter = customAdapter

//On Click for ListView Item


listview.setOnItemClickListener { adapterView, view, position, l ->

//Provide the data on Click position in our listview


val hashMap: HashMap<String, String> =
customAdapter.getItem(position) as HashMap<String, String>

Toast.makeText(this@MainActivity, "Name : " +


hashMap.get("name") + "\nVersion : " + hashMap.get("version"),
Toast.LENGTH_LONG).show()
}

searchView.setOnQueryTextListener(object :
SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}

override fun onQueryTextChange(newText: String?): Boolean {

val text = newText


/*Call filter Method Created in Custom Adapter
This Method Filter ListView According to Search Keyword
*/
customAdapter.filter(text)
return false
}
})

4. Now We have to Create Class CustomAdapter.

Right Click on Package name---->New--->Kotlin File/Class.

Now Select Class in Kind and Add name of Class.Here Our Class name is Custo
mAdapter.
5. After Class is Created add parameter to Class(passed in Main Activity) an
d extend with BaseAdapter()

Ex:

class CustomAdapter(context: Context, image: ArrayList<Int>, arrayList: ArrayL


ist<HashMap<String, String>>) : BaseAdapter() {

..

..

..

You will get Some Error Put Your Cursor on Red line And Press Alt+Enter and c
lick on Implement Members and Select All Methods and click Ok.

CustomAdapter.kt

package com.dharmendra.searchview

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import java.util.*
import kotlin.collections.ArrayList

/*We Have Created Constructor of Custom Adapter and Pass


context
ArrayList<Int> which Contain images
ArrayList<HashMap<String,String>> which contain name and
version*/

//Here We extend over Adapter With BaseAdapter()

class CustomAdapter(context: Context, image: ArrayList<Int>, arrayList:


ArrayList<HashMap<String, String>>) : BaseAdapter() {

//Passing Values to Local Variables


var image = image
var arrayList = arrayList
var context = context

//Store image and arraylist in Temp Array List we Required it later


var tempArrayList = ArrayList(image)
var tempNameVersionList = ArrayList(arrayList)

//Auto Generated Method


override fun getView(position: Int, convertView: View?, parent:
ViewGroup?): View {

var myview = convertView


val holder: ViewHolder

if (convertView == null) {

//If Over View is Null than we Inflater view using Layout


Inflater
val mInflater = (context as Activity).layoutInflater

//Inflating our list_row.


myview = mInflater!!.inflate(R.layout.list_row, parent, false)

//Create Object of ViewHolder Class and set our View to it


holder = ViewHolder()

//Find view By Id For all our Widget taken in list_row.

/*Here !! are use for non-null asserted two prevent From null.
you can also use Only Safe (?.)

*/
holder.mImageView =
myview!!.findViewById<ImageView>(R.id.imageview) as ImageView
holder.mHeader = myview!!.findViewById<TextView>(R.id.header)
as TextView
holder.mSubHeader =
myview!!.findViewById<TextView>(R.id.subHeader) as TextView

//Set A Tag to Identify our view.


myview.setTag(holder)
} else {
//If Ouer View in not Null than Just get View using Tag and
pass to holder Object.
holder = myview!!.getTag() as ViewHolder
}

//Getting HasaMap At Perticular Position


val map = arrayList.get(position)

//Setting Image to ImageView by position


holder.mImageView!!.setImageResource(image[position])

//Setting name to TextView it's Key from HashMap At Position


holder.mHeader!!.setText(map.get("name"))

//Setting version to TextView it's Key from HashMap At Position


holder.mSubHeader!!.setText(map.get("version"))

return myview

//Auto Generated Method


override fun getItem(p0: Int): Any {

//Return the Current Position of ArrayList.


return arrayList.get(p0)

//Auto Generated Method


override fun getItemId(p0: Int): Long {
return 0
}

//Auto Generated Method

override fun getCount(): Int {

//Return Size Of ArrayList


return arrayList.size
}

//Create A class To hold over View like we taken in list_row.xml


class ViewHolder {

var mImageView: ImageView? = null


var mHeader: TextView? = null
var mSubHeader: TextView? = null
}

//Function to set data according to Search Keyword in ListView


fun filter(text: String?) {
//Our Search text
val text = text!!.toLowerCase(Locale.getDefault())

//Here We Clear Both ArrayList because We update according to


Search query.
image.clear()
arrayList.clear()

if (text.length == 0) {

/*If Search query is Empty than we add all temp data into our
main ArrayList

We store Value in temp in Starting of Program.

*/

image.addAll(tempArrayList)
arrayList.addAll(tempNameVersionList)

} else {

for (i in 0..tempNameVersionList.size - 1) {

/*
If our Search query is not empty than we Check Our search
keyword in Temp ArrayList.
if our Search Keyword in Temp ArrayList than we add to our
Main ArrayList
*/

if
(tempNameVersionList.get(i).get("name")!!.toLowerCase(Locale.getDefault()).
contains(text)) {

image.add(tempArrayList.get(i))
arrayList.add(tempNameVersionList.get(i))

}
}

//This is to notify that data change in Adapter and Reflect the


changes.
notifyDataSetChanged()

}
}

Output:

You might also like