Exibir collections - SDK Java
Nesta página
Os aplicativos Android geralmente preenchem a interface do usuário usando RecyclerView ou ListView componentes. O Realm oferece adaptadores para exibir coleções de objeto OrderedRealmCollections
de Realm . Essas coleções implementam a interface . RealmResults e RealmList são exemplos desses adaptadores. Com esses adaptadores, os componentes da interface do usuário são atualizados quando o aplicativo altera os objetos de Realm .
Instalar adaptadores
Adicione estas dependências ao seu arquivo de nível de aplicativo build.gradle
:
dependencies { implementation 'io.realm:android-adapters:4.0.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' }
O Realm hospeda esses adaptadores no JCenter repositório de artefatos. Para usar jcenter
em seu aplicativo Android, adicione-o ao arquivo build.gradle
no nível do projeto:
buildscript { repositories { jcenter() } } allprojects { repositories { jcenter() } }
Modelos de exemplo
Os exemplos nesta página usam um Objeto de Realm chamado Item
. Esta classe contém uma string chamada "name" e um número identificador chamado "ID":
import io.realm.RealmObject; public class Item extends RealmObject { int id; String name; public Item() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
import io.realm.RealmObject open class Item(var id: Int = 0, var name: String? = null): RealmObject()
Exibir collection em um ListView
Exibir Realm de domínio em um ListView estendendo o RealmBaseAdapter. O adaptador utiliza a interface ListAdapter
. A implementação funciona como qualquer ListAdapter
. Isso oferece suporte para a atualização automática de objetos do Realm .
Subclasse RealmBaseAdapter
para exibir objetos Item em um ListView
:
import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.TextView; import com.mongodb.realm.examples.model.java.Item; import io.realm.OrderedRealmCollection; import io.realm.RealmBaseAdapter; class ExampleListAdapter extends RealmBaseAdapter<Item> implements ListAdapter { String TAG = "REALM_LIST_ADAPTER"; ExampleListAdapter(OrderedRealmCollection<Item> realmResults) { super(realmResults); } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { Log.i(TAG, "Creating view holder"); // create a top-level layout for our item views LinearLayout layout = new LinearLayout(parent.getContext()); layout.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // create a text view to display item names TextView titleView = new TextView(parent.getContext()); titleView.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // attach the text view to the item view layout layout.addView(titleView); convertView = layout; viewHolder = new ViewHolder(titleView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } // as long as we if (adapterData != null) { final Item item = adapterData.get(position); viewHolder.title.setText(item.getName()); Log.i(TAG, "Populated view holder with data: " + item.getName()); } else { Log.e(TAG, "No data in adapter! Failed to populate view holder."); } return convertView; } private static class ViewHolder { TextView title; public ViewHolder(TextView textView) { title = textView; } } }
Para exibir dados de lista em uma atividade, instancie um ListView
. Em seguida, anexe um ExampleListAdapter
:
// instantiate a ListView programmatically ListView listView = new ListView(activity.getApplicationContext()); listView.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // create an adapter with a RealmResults collection // and attach it to the ListView ExampleListAdapter adapter = new ExampleListAdapter( realm.where(Item.class).findAll()); listView.setAdapter(adapter); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); activity.addContentView(listView, layoutParams);
import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.ListAdapter import android.widget.TextView import com.mongodb.realm.examples.model.kotlin.Item import io.realm.OrderedRealmCollection import io.realm.RealmBaseAdapter internal class ExampleListAdapter(realmResults: OrderedRealmCollection<Item?>?) : RealmBaseAdapter<Item?>(realmResults), ListAdapter { var TAG = "REALM_LIST_ADAPTER" override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val viewHolder: ViewHolder if (convertView == null) { Log.i(TAG, "Creating view holder") // create a top-level layout for our item views val layout = LinearLayout(parent.context) layout.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) // create a text view to display item names val titleView = TextView(parent.context) titleView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) // attach the text view to the item view layout layout.addView(titleView) convertView = layout viewHolder = ViewHolder(titleView) convertView.tag = viewHolder } else { viewHolder = convertView.tag as ViewHolder } // as long as we if (adapterData != null) { val item = adapterData!![position]!! viewHolder.title.text = item.name Log.i(TAG, "Populated view holder with data: ${item.name}") } else { Log.e(TAG, "No data in adapter! Failed to populate view holder.") } return convertView } private class ViewHolder(var title: TextView) }
Para exibir dados de lista em uma atividade, instancie um ListView
. Em seguida, anexe um ExampleListAdapter
:
// instantiate a ListView programmatically val listView = ListView(activity!!.applicationContext) listView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) // create an adapter with a RealmResults collection // and attach it to the ListView val adapter = ExampleListAdapter(realm.where(Item::class.java).findAll()) listView.adapter = adapter val layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) activity!!.addContentView(listView, layoutParams)
Exibir collection em um RecyclerView
Exibir objetos de Realm em um RecyclerView estendendo o RealmRecyclerViewAdapter. O adaptador estende RecyclerView.Adapter
. A implementação funciona como qualquer adaptador RecyclerView
. Isso oferece suporte para a atualização automática de objetos do Realm .
Subclasse RealmRecyclerViewAdapter
para exibir objetos Item em um RecyclerView
:
import android.util.Log; import android.view.ViewGroup; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.mongodb.realm.examples.model.java.Item; import io.realm.OrderedRealmCollection; import io.realm.RealmRecyclerViewAdapter; /* * ExampleRecyclerViewAdapter: extends the Realm-provided * RealmRecyclerViewAdapter to provide data * for a RecyclerView to display * Realm objects on screen to a user. */ class ExampleRecyclerViewAdapter extends RealmRecyclerViewAdapter<Item, ExampleRecyclerViewAdapter.ExampleViewHolder> { String TAG = "REALM_RECYCLER_ADAPTER"; ExampleRecyclerViewAdapter(OrderedRealmCollection<Item> data) { super(data, true); Log.i(TAG, "Created RealmRecyclerViewAdapter for " + getData().size() + " items."); } public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Log.i(TAG, "Creating view holder"); TextView textView = new TextView(parent.getContext()); textView.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); return new ExampleViewHolder(textView); } public void onBindViewHolder(ExampleViewHolder holder, int position) { final Item obj = getItem(position); Log.i(TAG, "Binding view holder: " + obj.getName()); holder.data = obj; holder.title.setText(obj.getName()); } public long getItemId(int index) { return getItem(index).getId(); } class ExampleViewHolder extends RecyclerView.ViewHolder { TextView title; public Item data; ExampleViewHolder(TextView view) { super(view); title = view; } } }
Para exibir dados de lista em uma atividade, instancie um RecyclerView
. Em seguida, anexe um ExampleRecyclerViewAdapter
:
// instantiate a RecyclerView programmatically RecyclerView recyclerView = new RecyclerView(activity.getApplicationContext()); recyclerView.setLayoutManager( new LinearLayoutManager(activity.getApplicationContext())); recyclerView.setHasFixedSize(true); recyclerView.addItemDecoration(new DividerItemDecoration( activity.getApplicationContext(), DividerItemDecoration.VERTICAL)); // create an adapter with a RealmResults collection // and attach it to the RecyclerView ExampleRecyclerViewAdapter adapter = new ExampleRecyclerViewAdapter( realm.where(Item.class).findAll()); recyclerView.setAdapter(adapter); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); activity.addContentView(recyclerView, layoutParams);
import android.util.Log import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.mongodb.realm.examples.model.kotlin.Item import io.realm.OrderedRealmCollection import io.realm.RealmRecyclerViewAdapter /* * ExampleRecyclerViewAdapter: extends the Realm-provided * RealmRecyclerViewAdapter to provide data * for a RecyclerView to display * Realm objects on screen to a user. */ internal class ExampleRecyclerViewAdapter(data: OrderedRealmCollection<Item?>?) : RealmRecyclerViewAdapter<Item?, ExampleRecyclerViewAdapter.ExampleViewHolder?>(data, true) { var TAG = "REALM_RECYCLER_ADAPTER" override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder { Log.i(TAG, "Creating view holder") val textView = TextView(parent.context) textView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) return ExampleViewHolder(textView) } override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) { val obj = getItem(position) Log.i(TAG, "Binding view holder: ${obj!!.name}") holder.data = obj holder.title.text = obj.name } override fun getItemId(index: Int): Long { return getItem(index)!!.id.toLong() } internal inner class ExampleViewHolder(var title: TextView) : RecyclerView.ViewHolder(title) { var data: Item? = null } init { Log.i(TAG, "Created RealmRecyclerViewAdapter for ${getData()!!.size} items.") } }
Para exibir dados de lista em uma atividade, instancie um RecyclerView
. Em seguida, anexe um ExampleRecyclerViewAdapter
:
// instantiate a RecyclerView programmatically val recyclerView = RecyclerView(activity!!.applicationContext) recyclerView.layoutManager = LinearLayoutManager(activity!!.applicationContext) recyclerView.setHasFixedSize(true) recyclerView.addItemDecoration( DividerItemDecoration(activity!!.applicationContext, DividerItemDecoration.VERTICAL)) // create an adapter with a RealmResults collection // and attach it to the RecyclerView val adapter = ExampleRecyclerViewAdapter(realm.where(Item::class.java).findAll()) recyclerView.adapter = adapter val layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) activity!!.addContentView(recyclerView, layoutParams)