There are three fragments i.e., faculty, students, mentees. I want to search active fragment recycle adapter items.
Using search view as you see in the picture.
Here I am furnishing the code:
I am not able to implement
private fun filter(msg: String) {
}
in MainActivity.kt because as you know that fragments are not active and got the same error message after trying to implement it.
MainActivity.kt
package edu.cvr.csecontacts
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.widget.SearchView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import edu.cvr.csecontacts.faculty.Faculty
import edu.cvr.csecontacts.faculty.FacultyRecycleAdaptor
import edu.cvr.csecontacts.mentees.MenteeData
import edu.cvr.csecontacts.mentees.MenteeRecycleAdapter
import edu.cvr.csecontacts.mentees.Mentees
import edu.cvr.csecontacts.students.StudentData
import edu.cvr.csecontacts.students.StudentRecycleAdaptor
import edu.cvr.csecontacts.students.Students
import java.io.BufferedReader
import java.io.InputStreamReader
class MainActivity : AppCompatActivity() {
lateinit var bottomNav: BottomNavigationView
private lateinit var facultyAdapter: FacultyRecycleAdaptor
private lateinit var menteeAdapter: MenteeRecycleAdapter
private lateinit var studentAdapter: StudentRecycleAdaptor
// val staff = InputStreamReader(assets.open("staff_contacts.csv"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = DBHelper(this, null)
val cursor = db.getName()
val faculty = Faculty()
val students = Students()
val mentees = Mentees()
loadFragment(Faculty())
db.deleteFaculty()
db.deleteMentees()
db.deleteStudents()
var tempArrayList: ArrayList<MenteeData>
val student = InputStreamReader(assets.open("mentees.csv"))
val reader = BufferedReader(student)
var line : String?
tempArrayList = arrayListOf()
while (reader.readLine().also { line = it } != null){
val row : List<String> = line!!.split(",")
//tempArrayList!!.add(FacultyData(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10]))
db.addStudents(row[0],row[1],row[2])
db.addMentees(row[0],row[1],row[2])
}
val facultyData = InputStreamReader(assets.open("staff_contacts.csv"))
val reader1 = BufferedReader(facultyData)
var line1 : String?
// tempArrayList = arrayListOf()
while (reader1.readLine().also { line1 = it } != null){
val row : List<String> = line1!!.split(",")
//tempArrayList!!.add(FacultyData(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10]))
db.addName(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10])
}
//Faculty.newInstance(tempArrayList)
var bottomNav:BottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNav)
bottomNav.setOnItemSelectedListener {
when(it.itemId){
R.id.faculty ->loadFragment(Faculty())
R.id.students->loadFragment(students)
else -> {loadFragment(mentees)}
}
true
}
}
private fun loadFragment(fragment: Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.container, fragment)
commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater: MenuInflater = getMenuInflater()
inflater.inflate(R.menu.menu_item, menu)
val item = menu?.findItem(R.id.search_action)
val searchView = item?.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if (newText != null) {
filter(newText)
}
return true
}
})
return true
}
private fun filter(msg: String) {
}
}
Faculty.kt
package edu.cvr.csecontacts.faculty
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import edu.cvr.csecontacts.DBHelper
import edu.cvr.csecontacts.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [Faculty.newInstance] factory method to
* create an instance of this fragment.
*/
class Faculty : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var facultyAdapter: FacultyRecycleAdaptor
override fun onCreate(savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_faculty, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
attachAdapter(view)
}
private fun attachAdapter(view: View) {
val db = DBHelper(view.context,null)
val rv = view.findViewById<RecyclerView>(R.id.faculty_fragment)
rv.layoutManager = LinearLayoutManager(view.context)
val data = db.listUser()
rv.adapter = FacultyRecycleAdaptor(data)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Faculty.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
Faculty().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
FacultyRecycleAdaptor.kt
package edu.cvr.csecontacts.faculty
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import edu.cvr.csecontacts.FacultyData
import edu.cvr.csecontacts.R
class FacultyRecycleAdaptor(var tempArrayList: ArrayList<FacultyData>) : RecyclerView.Adapter<FacultyRecycleAdaptor.ViewHolder>() {
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
lateinit var name:TextView
lateinit var designation:TextView
lateinit var call: ImageButton
lateinit var msg: ImageButton
lateinit var whatsapp: ImageButton
init {
name =itemView.findViewById(R.id.title)
designation = itemView.findViewById(R.id.subname)
call = itemView.findViewById(R.id.call)
msg = itemView.findViewById(R.id.msg)
whatsapp = itemView.findViewById(R.id.whatsapp)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): ViewHolder {
val v =LayoutInflater.from(parent.context).inflate(R.layout.card_layout, parent,false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.name.setText(tempArrayList[position].name)
holder.designation.setText(tempArrayList[position].designation)
val context = holder.name.context
holder.call.setOnClickListener(){
val number = tempArrayList[position].college_mail_id.trim()
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(number)))
context.startActivity(intent)
}
holder.msg.setOnClickListener() {
val number = tempArrayList[position].college_mail_id.trim()
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("sms:" + Uri.encode(number)))
context.startActivity(intent)
// startActivity(intent)
}
holder.whatsapp.setOnClickListener() {
val number = tempArrayList[position].college_mail_id.trim()
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("sms:" + Uri.encode(number)))
intent.setPackage("com.whatsapp")
context.startActivity(intent)
// startActivity(intent)
}
}
override fun getItemCount(): Int {
return this.tempArrayList.size
}
fun filterList(facultyFilteredList: ArrayList<FacultyData>) {
tempArrayList = facultyFilteredList
notifyDataSetChanged()
}
}
DBHelper.kt
package edu.cvr.csecontacts
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import edu.cvr.csecontacts.mentees.MenteeData
import edu.cvr.csecontacts.students.StudentData
class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {
// below is the method for creating a database by a sqlite query
override fun onCreate(db: SQLiteDatabase) {
// below is a sqlite query, where column names
// along with their data types is given
val query = ("CREATE TABLE " + TABLE_NAME_1 + " ("
+ ID_COL+" TXT," +
NAME_COL + " TEXT," +
GENDER_COL + " TEXT," +
DESIGNATION_COL + " TEXT," +
CONTACT_COL + " TEXT," +
CVRMAIL_COL + " TEXT," +
MAIL_COL + " TEXT," +
DOJ_COL + " TEXT," +
DOB_COL + " TEXT," +
AADHAR_COL + " TEXT," +
PAN_COL + " TEXT" + ")")
val query2 = ("CREATE TABLE " + TABLE_NAME_2 + " ("
+ ROLL_COL+" TXT," +
NAME_COL + " TEXT," +
CONTACT_COL + " TEXT" + ")")
val query3 = ("CREATE TABLE " + TABLE_NAME_3 + " ("
+ ROLL_COL+" TXT," +
NAME_COL + " TEXT," +
CONTACT_COL + " TEXT" + ")")
// we are calling sqlite
// method for executing our query
try {
db.execSQL(query2)
}catch (e: SQLException){
e.printStackTrace()
}
db.execSQL(query)
db.execSQL(query3)
}
override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
// this method is to check if table already exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_1)
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2)
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3)
onCreate(db)
}
// This method is for adding data in our database
fun addName(id: String,name : String,gender: String, designation : String, contact: String, cvrmail:String, personal_mail:String,doj: String, dob:String, aadhar:String, pan:String ){
// below we are creating
// a content values variable
val values = ContentValues()
// we are inserting our values
// in the form of key-value pair
values.put(ID_COL,id)
values.put(NAME_COL, name)
values.put(GENDER_COL,gender)
values.put(DESIGNATION_COL, designation)
values.put(CONTACT_COL, contact)
values.put(CVRMAIL_COL, cvrmail)
values.put(MAIL_COL,personal_mail)
values.put(DOJ_COL,doj)
values.put(DOB_COL,dob)
values.put(AADHAR_COL,aadhar)
values.put(PAN_COL,pan)
// here we are creating a
// writable variable of
// our database as we want to
// insert value in our database
val db = this.writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME_1, null, values)
// at last we are
// closing our database
//db.close()
}
// below method is to get
// all data from our database
fun getName(): Cursor? {
// here we are creating a readable
// variable of our database
// as we want to read value from it
val db = this.readableDatabase
// below code returns a cursor to
// read data from the database
return db.rawQuery("SELECT * FROM " + TABLE_NAME_1, null)
}
fun listUser(): ArrayList<FacultyData> {
val db = this.readableDatabase
val storeUserInfo = ArrayList<FacultyData>()
val curs = db.rawQuery("SELECT * FROM " + TABLE_NAME_1,null)
if (curs!!.moveToFirst()){
do {
val id = curs!!.getString(0)
val name = curs!!.getString(1)
val gender = curs!!.getString(2)
val designation = curs!!.getString(3)
val mobN = curs!!.getString(3)
val cvr_mail = curs!!.getString(4)
val email = curs!!.getString(5)
val doj = curs!!.getString(6)
val dob = curs!!.getString(7)
val aadhar = curs!!.getString(7)
val pan = curs!!.getString(8)
storeUserInfo.add(FacultyData(id,name,gender,designation,mobN,cvr_mail,email,doj,dob,aadhar,pan))
} while (curs!!.moveToNext())
}
curs!!.requery()
// curs!!.close()
return storeUserInfo
}
fun deleteFaculty(){
val db = this.readableDatabase
db.execSQL("DELETE from "+ TABLE_NAME_1)
}
fun deleteStudents(){
val db = this.readableDatabase
db.execSQL("DELETE from "+ TABLE_NAME_3)
}
fun deleteMentees(){
val db = this.readableDatabase
db.execSQL("DELETE from "+ TABLE_NAME_2)
}
fun addMentees(rollNo:String,name:String,mobile:String){
val values = ContentValues()
values.put(ROLL_COL,rollNo)
values.put(NAME_COL,name)
values.put(CONTACT_COL, mobile)
val db = this.writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME_2, null, values)
}
fun listMentees():ArrayList<MenteeData>{
val db = this.readableDatabase
val storeMenteeInfo = ArrayList<MenteeData>()
val curs = db.rawQuery("SELECT * FROM " + TABLE_NAME_2,null)
if (curs!!.moveToFirst()) {
do {
val rollNo = curs!!.getString(0)
val name = curs!!.getString(1)
val mobile = curs!!.getString(2)
storeMenteeInfo.add(MenteeData(rollNo, name, mobile))
} while (curs!!.moveToNext())
}
curs!!.requery()
//curs!!.close()
return storeMenteeInfo
}
fun addStudents(rollNo:String,name:String,mobile:String){
val values = ContentValues()
values.put(ROLL_COL,rollNo)
values.put(NAME_COL,name)
values.put(CONTACT_COL, mobile)
val db = this.writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME_3, null, values)
}
fun listStudents():ArrayList<StudentData>{
val db = this.readableDatabase
val storeStudentInfo = ArrayList<StudentData>()
val curs = db.rawQuery("SELECT * FROM " + TABLE_NAME_3,null)
if (curs!!.moveToFirst()) {
do {
val rollNo = curs!!.getString(0)
val name = curs!!.getString(1)
val mobile = curs!!.getString(2)
storeStudentInfo.add(StudentData(rollNo, name, mobile))
} while (curs!!.moveToNext())
}
curs!!.requery()
//curs!!.close()
return storeStudentInfo
}
companion object{
// here we have defined variables for our database
// below is variable for database name
private val DATABASE_NAME = "cse"
// below is the variable for database version
private val DATABASE_VERSION = 1
// below is the variable for table name
val TABLE_NAME_1 = "faculty"
val TABLE_NAME_2 = "mentees"
val TABLE_NAME_3 = "students"
// below is the variable for id column
val ID_COL = "id"
val ROLL_COL = "roll_no"
// below is the variable for name column
val NAME_COL = "name"
val GENDER_COL = "gender"
val DESIGNATION_COL = "designation"
val CONTACT_COL = "contact"
val CVRMAIL_COL = "cvrmail_id"
val MAIL_COL = "personnel_mail"
val DOJ_COL = "doj"
val DOB_COL = "dob"
val AADHAR_COL = "aadhar"
val PAN_COL = "pan"
}
}