How to update my Recyclerview using kotlin android

2019-08-28 01:05发布

问题:

I have an actitvity with Recyclerview which display data. Now I want to update my RecyclerView once got a new data.For now each time I close and reopen my app the new data will be displayed. but i want it without close to update my view.

I have tried this,

but nothing will work,

fun setupViewPager(viewPager: ViewPager, it: List<TransactionEntity>, incoming: TransactionAdapterDirection, mainActivity: MainActivity) {

        val cc: Context = mainActivity.applicationContext

        if(adapter.count < 2) {
            if (incoming.equals(OUTGOING)) {
                val gson = Gson()
                val gson1 = GsonBuilder().create()
                val model = it
                val IT = gson.toJson(model)

                val pref = cc.applicationContext.getSharedPreferences("MyPrefSend", 0)
                val editor = pref.edit()
                editor.putString("NEWIT_SEND", IT)
                editor.apply()

                adapter.addFragment(SendingFragment(),"SEND")
                adapter.notifyDataSetChanged()
            } else if (incoming.equals(INCOMING)) {
                val gson = Gson()
                val gson1 = GsonBuilder().create()
                val model = it
                val IT = gson.toJson(model)

                val pref = cc.applicationContext.getSharedPreferences("MyPrefRec", 0)
                val editor = pref.edit()
                editor.putString("NEWIT_REC", IT)
                editor.apply()
                adapter.addFragment(ReceiveFragment(), "RECEIVE")
                adapter.notifyDataSetChanged()
            }
            viewPager.adapter = adapter
        }
    }


class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager)
    {
        private val mFragmentList: ArrayList<Fragment> = ArrayList<Fragment>()
        private val mFragmentTitleList: ArrayList<String>  = ArrayList<String>()

        override fun getCount(): Int {
            return mFragmentList.size
        }


        override fun getItem(position: Int): Fragment? {
            var fragment: Fragment? = null
            if (position == 0) {
                fragment = SendingFragment()
            } else if (position == 1) {
                fragment = ReceiveFragment()
            }
            return fragment
        }


        fun addFragment(fragment: Fragment, title: String) {
            mFragmentList.add(fragment)
            mFragmentTitleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return mFragmentTitleList[position]
        }

        override fun getItemPosition(fragItem: Any): Int {
            var position = 0
            if (fragItem is ReceiveFragment) {
                position = 0
            } else if (fragItem is SendingFragment) {
                position = 1
            }
            return if (position >= 0) position else PagerAdapter.POSITION_NONE
        }
    }

**Framgnet.kt**





class ReceiveFragment: Fragment()
    {

        private var linearLayoutManager: LinearLayoutManager? = null

        fun fromJson(jsonString: String, type: Type): Any {
            return Gson().fromJson(jsonString, type)
        }

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

            val pref = context!!.getSharedPreferences("MyPrefRec", 0)
            val mFragIT = pref.getString("NEWIT_REC", "")

            val NewIT = fromJson(mFragIT,
                    object : TypeToken<List<TransactionEntity>>() {

                    }.type) as List<TransactionEntity>

            val activity = activity  as MainActivity
            val myAppDatabaseData = activity.getAppDatabaseData()
            val myNetwrk = activity.getNwtwrkData()

            // Inflate the layout for this fragment
            val rootView = inflater.inflate(R.layout.receive_fragment, container, false)
            val recyclerView = rootView.findViewById<RecyclerView>(R.id.transaction_recycler_in) as RecyclerView
            linearLayoutManager = LinearLayoutManager(activity, LinearLayout.VERTICAL, false)
            recyclerView.layoutManager = linearLayoutManager
            recyclerView.adapter = TransactionRecyclerAdapter(NewIT,myAppDatabaseData,TransactionAdapterDirection.INCOMING,myNetwrk)
            recyclerView.setHasFixedSize(true)
            return rootView
        }

    }

I have tried this, mAdapter.notifyDataSetChanged();

回答1:

You can do it with a function in your ItemAdapter:

/**
 * Refresh the whole data set of items.
 */
fun refreshDataset() {
    mDataset = parseItems(mAppCtx)
    notifyDataSetChanged()
}

and then, any time you receive a new set of data, you can call such function directly.



回答2:

If you want to update data from activity/fragment than you can make one function inside adapter as below:

 public void update(ArrayList<String> modelList){
        //string arraylist is for example pass your data
        // replace your adapter data with argument data
       mAdapter.notifyDataSetChanged();
    }

For kotlin:

fun update(modelList:ArrayList<String){
   myList = modelList
   myAdapter!!.notifyDataSetChanged()
}

Call this function from activity/fragment as below :

 mAdapter.update(response.getList());


回答3:

If you want to do in more Kotlin style do like this:

1) Create an abstract class for Adapter:

 abstract class BaseRecyclerAdapter<Type, ViewHolder : BaseViewHolder<Type>>(list: List<Type> = mutableListOf()) : RecyclerView.Adapter<ViewHolder>() {

   var items: MutableList<Type> = list.toMutableList()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    override fun getItemCount() = items.size
    enter code here
    override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position]) }

2) Create an abstract class for ViewHolder:

 abstract class BaseViewHolder<in T>(override val containerView: View): RecyclerView.ViewHolder(containerView), LayoutContainer {

    abstract fun bind(item: T) }

3) How to use:

class MyActivity : AppCompatActivity() { private var adapter: MyAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        //This is your data which you set first time
        val initData = mutableListOf<String>()
        adapter = MyAdapter(initData)
        myRecyclerView.layoutManager = adapter
        myRecyclerView.layoutManager = LinearLayoutManager(this)
    }
    // Call this function when you need to update adapter
    private fun notifyAdapter(list: MutableList<String>){
        adapter.items = list 
    }}

Create MyAdapter:

 private class MyAdapter(list: MutableList<String>) : BaseRecyclerAdapter<String, ViewHolder>(list) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.newInstance(parent)

    }

Create ViewHolder for MyAdapter:

private class ViewHolder(containerView: View) : BaseViewHolder<String>(containerView) {

    companion object {
        fun newInstance(parent: ViewGroup) = ViewHolder(parent.inflate(R.layout.item))
    }

    override fun bind(item: String) {
        title.text = item
    }}

Create item for ViewHolder:

  <?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="wrap_content">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </LinearLayout>

If you have any questions please ask



回答4:

You should try LiveData

LiveData is a data holder class that can be observed within a given lifecycle. This means that an Observer can be added in a pair with a LifecycleOwner, and this observer will be notified about modifications of the wrapped data only if the paired LifecycleOwner is in active state.

Documentation: https://developer.android.com/reference/android/arch/lifecycle/LiveData