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();
Related
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
I am using a singleton for fetching data from a web service and storing the resulting data object in an ArrayList. It looks like this:
public class DataHelper {
private static DataHelper instance = null;
private List<CustomClass> data = null;
protected DataHelper() {
data = new ArrayList<>();
}
public synchronized static DataHelper getInstance() {
if(instance == null) {
instance = new DataHelper();
}
return instance;
}
public void fetchData(){
BackendlessDataQuery query = new BackendlessDataQuery();
QueryOptions options = new QueryOptions();
options.setSortBy(Arrays.asList("street"));
query.setQueryOptions(options);
CustomClass.findAsync(query, new AsyncCallback<BackendlessCollection<CustomClass>>() {
#Override
public void handleResponse(BackendlessCollection<CustomClass> response) {
int size = response.getCurrentPage().size();
if (size > 0) {
addData(response.getData());
response.nextPage(this);
} else {
EventBus.getDefault().post(new FetchedDataEvent(data));
}
}
#Override
public void handleFault(BackendlessFault fault) {
EventBus.getDefault().post(new BackendlessFaultEvent(fault));
}
});
}
public List<CustomClass> getData(){
return this.data;
}
public void setData(List<CustomClass> data){
this.data = data;
}
public void addData(List<Poster> data){
this.data.addAll(data);
}
public List<CustomClass> getData(FilterEnum filter){
if(filter == FilterEnum.NOFILTER){
return getData();
}else{
// Filtering and returning filtered data
}
return getData();
}
}
The data is fetched correctly and the list actually contains data after it. Also, only one instance is created, as intended. However, whenever I call getData later, the length of this.data is 0. Because of this I also tried it with a subclass of Application holding the DataHelper object, resulting in the same problem.
Is there a good way of debugging this? Is there something like global watches in Android Studio?
Is there something wrong with my approach? Is there a better approach? I am mainly an iOS developer, so Android is pretty new to me. I am showing the data from the ArrayList in different views, thus I want to have it present in an the ArrayList as long as the application runs.
Thanks!
EDIT: Example use in a list view fragment (only relevant parts):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = FilterEnum.NOFILTER;
data = DataHelper.getInstance().getData(filter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
customClassListAdapter = new customClassListAdapter(getActivity(), data);}
EDIT2: Added code where I fetch the data from Backendless, changed reference of DataHelper to reference of data in first EDIT
EDIT3: I usa a local EventBus for notifying the list view about the new data. This looks like this and works (initially the data gets populated, but after e.g. applying a filter, the ArrayList I get with getData is empty):
#Subscribe
public void onMessageEvent(FetchedDataEvent event) {
customClassListAdapter.notifyDataSetChanged();
}
Try instead of keeping reference to your DataHelper instance, keeping reference to your list of retrieved items. F.e. when you first fetch the list (and it's ok as you say), assign it to a class member. Or itarate through it and create your own array list of objects for future use.
Okay I finally found the problem. It was not about the object or memory management at all. Since I give the reference on getData to my ArrayAdapter, whenever I call clear (which I do when changing the filter) on the ArrayAdapter, it empties the reference. I basically had to create a copy of the result for the ArrayAdapter:
data = new ArrayList<>(DataHelper.getInstance().getData(filter));
I was not aware of the fact that this is a reference at all. So with this the data always stays in the helper entirely. I only did this because this:
customClassListAdapter.notifyDataSetChanged();
does hot help here, it does not call getData with the new filter again.
Thanks everyone for your contributions, you definitely helped me to debug this.
It is likely that getData does get called before the data is filled.
A simple way to debug this is to add (import android.util.Log) Log.i("MyApp.MyClass.MyMethod", "I am here now"); entries to strategic places in fetchData, addData and getData and then, from the logs displayed by adb logcat ensure the data is filled before getData gets called.
what i have is three activities, the first one called penddingorders which i make an array list inside it and i add strings to it like this :
ArrayList prodlist=new ArrayList();
for(int z=0;z<=mylist.size();z++){
if(id.equals(mylist.get(arg2).getOrderId()))
{
product=mylist.get(arg2).getProductName();
quantity=mylist.get(arg2).getQuantity();
unit=mylist.get(arg2).getUnit();
price=mylist.get(arg2).getPrice();
totalprice=mylist.get(arg2).getTotalPrice();
totalpriceAfterDiscount=mylist.get(arg2).getPriceAfterDiscount();
note=mylist.get(arg2).getNote();
prodlist.add(product);
prodlist.add(quantity);
prodlist.add(unit);
prodlist.add(totalprice);
prodlist.add(price);
prodlist.add(totalpriceAfterDiscount);
prodlist.add(note);
arg2++;
}
and i have print it in the logcat and it shows correctly:
Log.e("product list",prodlist+"");
and i have send it from the first activity to the third activity like this , though i should pass through the second one before i go to the third one :
Intent intent = new Intent(PenddingOrders.this, ProductInfoDetails.class);
intent.putStringArrayListExtra("prodlist", prodlist);
startActivity(intent);
and in the third activity i get the array list through this code :
try{
prodlist = getIntent().getStringArrayListExtra("prodlist");
}
catch(Exception e){
e.printStackTrace();
}
Log.e("prodlist",prodlist+"");
but in the logcat i get null value .. so what i am doing wrong please help ??
you can set your property using getter setter so you can manage your value very well.
and make it parceable. so you can use it Extras ArrayList of it into next Activity.
Please follow this https://stackoverflow.com/a/15731120/942224
This is my ans on stackoverflow please checked and hope it's help alot:
Java / Android ArrayList in different Activity
Better to use Android Application class to persist data.
For reference link
public class MyApplication extends Application {
private ArrayList<String> list;
public void setValue(ArrayList<String> list) {
this.list = list;
}
public ArrayList<String> getValue() {
return list;
}
}
Step-1
First set the value from your Activity
MyApplication globalVariable = (MyApplication) getApplicationContext();
globalVariable.setValue(prodlist)// Set your ArraList that you want to store
Step-2
Retrieve the value in other activity like
MyApplication globalVariable = (MyApplication) getApplicationContext();
// Get ArrayList from global/application context
ArrayList<String> list = globalVariable.getValue();
and don't forget to register in Manifest.xml
<application
android:name="YOUR_PACKAGE_NAME.MyApplication "
-----------------------
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);
In my Android app I have multiple activities using different array resources and I want to create one that has all of them. Is there an easy way to do this so that when I add an item to the string array it is automatically added to the "All" activity?
You need to create a generalized array in a class called ConstantCodes.java and declare your all arrays in it as follows,
public class ConstantCodes
{
public static String[][] arrayCollection = { { "A11","A22","A33" },
{ "B11","B22","B33" },
{ "C11","C22","C33" }
};
}
Calling FirstActivity.java
private String[] firstActivityArray = ConstantCodes.arrayCollection[0]; // this will return first stored array on 0th position.
Calling SecondActivity.java
private String[] secondActivityArray = ConstantCodes.arrayCollection[1]; // this will return first stored array on 1st position.