How to send data between one adapter to another adapter? - android

Actually, I have a Recyclerview where has a button and(where I get id with position[from RestAPi call])--->>when the button is clicked I set another recylerview..and now I want to the from the first RecyclerviewAdapter.
I have already tried global variable
Here is images enter image description here

From my previous answer from another question i think you need a Singleton Pattern rather than a Global Variable
You simply need a getter that returns the another Adapter's ArrayList<SingleItemModel> but the problem you will face is that you need to have the same instance of the Adapter from the Activity in order to get the populated ArrayList<Model>.
A good workaround is to used Bill Pugh's Singleton in the Adapter
public class Adapter {
private ArrayList<Model> list;
private Adapter() {}
public static Adapter getInstance() {
return InstInit.INSTANCE;
}
// Don't forget to set the list (or NPE)
// because we can't argue with a Singleton
public void setList(ArrayList<Model> list) {
this.list = list;
}
// You can now get the ArrayList
public ArrayList<Model> getList() {
return list;
}
private static class InstInit {
private static final Adapter INSTANCE = new Adapter();
}
// Some codes removed for brevity
// Overrided RecyclerView.Adapter Methods
.................
}
Retrieving the ArrayList assuming that the following Adapters are Singleton
AdapterOne a1 = AdapterOne.getInstance();
AdapterTwo a2 = AdapterTwo.getInstance();
ArrayList<Model> a1RetrievedList = a1.getList();
// You don't need to create a new instance
// creating a new instance doesn't make sense
// because you need to repopulate the list
// for the new instance.
ArrayList<Model> a2RetrievedList = a2.getList();
// You can also retrieve from AdapterTwo

Related

How to bind live data to array adapter android

I have a simple application while I'm trying to understand android/room. I would like to have my query from room to be placed into my list view.
PersonDao.class
#Query("Select name from People limit 3")
LiveData<List<String>> getThreeNames();
AvtivityMain.class
private ArrayAdapter<String> adapter;
private PersonDatabase db;
private EditText age;
private EditText name;
Person person;
private DatabaseRepository rDb;
private PersonViewModel personViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
age = findViewById(R.id.age);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
ListView lvPerson = findViewById(R.id.lv3Poeple);
lvPerson.setAdapter(adapter);
personViewModel = ViewModelProviders.of(this).get(PersonViewModel.class);
}
public void addPerson(View view){
int sAge = Integer.parseInt(age.getText().toString());
String sName = name.getText().toString();
person = new Person(sName, sAge);
personViewModel.insert(person);
System.out.println(personViewModel.getmAllPeople());
System.out.println(personViewModel.getm3People());
//List<String> names = personViewModel.getm3People();
//adapter.add(personViewModel.getm3People());
}
I have commented out the code I am having problems with. I want to be able to use my query from PersonDao and have my list view show 3 names from my Room database.
You need to do a few things, the first is make sure your adapter can take new input. I would suggest creating your own custom one. When you do create it, be sure to include a method that takes your person strings as input and notifies the adapter of the change, like so:
//you need to add an update method to your adapter, so it can change it's data as your
//viewmodel data changes, something like this:
public void setPersons(List<String> personNames) {
//myPersons should be a variable declared within your adapter that the views load info from
myPersons = personNames;
notifyDataSetChanged();
}
Then in your activity you should set the Adapter as a global variable so it can be accessed by multiple methods, such as your view model observer method and it's initial setup in onCreate().
//need to set up adapter variable to access in other methods to keep view model observer
//off the main thread
private ArrayAdapter myAdapter;
After that you can set up the following observer method for your ViewModel (assuming you created the ViewModel Class properly with a return method called getThreeNames() and that isn't just within your DAO as you showed above.
//set up the view model observer to be off the main thread so it isn't tied to your main
//activity lifecyle (which is the whole point/beauty of the ViewModel), you can call this
//method in your onCreate() method and should stay until onDestroy() is called
private void setupPersonViewModel() {
PersonViewModel viewModel
= ViewModelProviders.of(this).get(PersonViewModel.class);
viewModel.getThreeNames().observe(this, new Observer<List<String>>() {
#Override
public void onChanged(#Nullable List<String> persons) {
//so you can see when your app does this in your log
Log.d(TAG, "Updating list of persons from LiveData in ViewModel");
mAdapter.setPersons(persons);
}
});
}
Hope that answers your question. Let me know if you need any further clarification.

Global data between activities [duplicate]

This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 6 years ago.
I have a activity that shows a list of products and a detail view where I can edit these products. I want to access the same list of products from both activities.
How do I store/use this global data between these multiple activities?
You may want to use a Singleton design pattern: create a class and limit it to have only one instance that will hold a list of products. After that, access this instance and the same list from both of your activities:
// singleton Manager
public class ProductManager {
private static ProductManager sInstance;
private List<Product> mProducts;
// private constructor to limit new instance creation
private ProductManager() {
// may be empty
}
public static ProductManager getInstance() {
if (sInstance == null) {
sInstance = new ProductManager();
}
return sInstance;
}
public List<Product> getProducts() {
return new ArrayList<>(mProducts);
}
// add logic to fill the Products list
public void setProducts(List<Product> products) {
mProducts = new ArrayList<>(products);
}
}
Access it later from both activities:
MyListActivity.java:
// set products once you get them
ProductManager.getInstance().setProducts(yourProductsList);
// ...
DetailsActivity.java:
// get the same list
ProductManager.getInstance().getProducts();
// ...
1) You can define array List as a static in Application Level or Base Activity.
2) Pass array List to other Activity using serializable or parcelable.
3) You have more data in array list then you can use SharedPreferences.

On Android, how can I build a Realm Adapter from a Realm List?

I'm writing a recipe app on Android using Realm. I have a RealmList of type Ingredient in each Recipe object. The object creation code is working fine.
Now I'm writing the code for the Fragment that displays a single recipe. I was able to create a Realm Adapter for the all recipe titles list, since I built that list using a query like so:
public class RecipeTitleAdapter extends RealmBaseAdapter<RecipeTitle> implements ListAdapter {
public RecipeTitleAdapter(Context context, int resId,
RealmResults<RecipeTitle> realmResults,
boolean automaticUpdate) {
...
recipeTitles = RecipeTitle.returnAllRecipeTitles(realm);
final RecipeTitleAdapter adapter = new RecipeTitleAdapter(RecipeParserApplication.appContext, R.id.recipe_list_view, recipeTitles, true);
But now that I'm looking at the ingredients for a single recipe, I have a RealmList of Ingredients and not a RealmResults object. My ingredient adapter class has the same type of constructor as the recipe titles adapter, so I want to know how (or even if) I can make it work starting with a RealmList.
public class IngredientAdapter extends RealmBaseAdapter<Ingredient> implements ListAdapter {
private static class ViewHolder {
TextView quantity;
TextView unitOfMeasure;
TextView ingredientItemName;
TextView processingInstructions;
}
public IngredientAdapter(Context context, int resId,
RealmResults<Ingredient> realmResults,
boolean automaticUpdate) {
....
final IngredientAdapter adapter = new IngredientAdapter(RecipeParserApplication.appContext, R.id.ingredientListView, recipe.getIngredients(), true);
public RealmList<Ingredient> getIngredients() {
return ingredients;
}
Since recipe.getIngredients returns a RealmList, the line where the IngredientAdapter is assigned returns a compile error:
Error:(63, 43) error: constructor IngredientAdapter in class IngredientAdapter cannot be applied to given types;
required: Context,int,RealmResults,boolean
found: Context,int,RealmList,boolean
reason: actual argument RealmList cannot be converted to RealmResults by method invocation conversion
A RealmList behaves like an normal array, so if you cannot make a query that matches what you want to display, you can just use any of the normal adapters like e.g. a ArrayAdapter. The only advantage of using a RealmBaseAdapter is that it autorefreshes, but that is fairly easy to accomplish yourself:
// Pseudo code
ArrayAdapter adapter;
RealmChangeListener listener = new RealmChangeListener() {
public void onChange() {
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
protected void onCreate(Bundle savedInstanceState) {
// ...
realm.addChangeListener(listener);
RealmList data = getRealmListData();
adapter = new ArrayAdapter(data);
listView.setAdapter(adapter);
}

Using a ForeignCollection

My entity contains the following private ForeignCollection attribute:
#ForeignCollectionField
private ForeignCollection<Order> orderCollection;
private List<Order> orderList;
What is the best way or usual way to avoid a having a caller use a ForeignCollection? Is there any neat way to return the Collections data to a caller?
How does the following method look? It allows a caller to access the data via a List. Would you recommend doing it this way?
public List<Order> getOrders() {
if (orderList == null) {
orderList = new ArrayList<Order>();
for (Order order : orderCollection) {
orderList.add(order);
}
}
return orderList;
}
If it's ok to change the signature to Collection rather than List, you could try using Collections.unmodifiableCollection().
public Collection<Order> getOrders()
{
return Collections.unmodifiableCollection(orderCollection);
}
Otherwise, your approach of using a lazy member variable is fine (provided you don't need synchronization). Also, note that you can just use the constructor of ArrayList to copy the values from the source collection:
orderList = new ArrayList<Order>(orderCollection);

How to Use ArrayList in more than one Activity?

How i can access ArrayList from one Activity to another and also clear ArrayList value?
you can use setter/getter method for it.
public class MySetGet
{
private ArrayList aList = null;
public void setList ( ArrayList aList )
{
this.aList = a.List;
}
public ArrayList getList ()
{
return aList;
}
}
Now you can set its value from any Activity/Class and get its value from any Activity/Class.
The most simply and possible way to do the desired::
1.Create a simple public class say Data..
Now create a public static your Array list object.
Now access any where..
Data.listObj
2.Create the List object as public static in one activity and use in another via,
SecondActivity.listObj.clear();

Categories

Resources