简体   繁体   中英

How to access ArrayList from another class in Android Java?

I'm new to Android and Java but do have some experience in Objective C and iPhone programming. I'm attempting to recreate an app I've already designed for the iPhone and am getting stuck on what should be a simple concept.

In my ParserHandler class I am parsing an XML from a server and putting the data into three separate ArrayList's. The parsing appears to be working fine. When I log and iterate through the ArrayList within my ParserHandler.java class it all works fine. (List1.java class has a few string variables and I've declared it like so in the ParserHandler: private List1 theList = new List1(); )

for(int i = 0; i<dogArray.size(); i++){
        theList = dogArray.get(i);
        Log.i(TAG, "looping " + i + " " + theList.Name);
        Log.i(TAG, "looping " + i + " " + theList.PhotoUrl);
        Log.i(TAG, "looping " + i + " " + theList.Type);


        }//this loops fine and has all the data

The dogArray is declared like so: public ArrayList<List1> dogArray = new ArrayList<List1>(); Now I want to access the dogArray from the class DogListView.java so in the onCreate method I attempt to do the following:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dog_list_view);
        ParserHandler ph = new ParserHandler();
        int d = ph.getNumberofDogs();
        int m = ph.dogArray.size();
        Log.i(TAG, "dog size is:" + d + "and:" + m);}

I've tried two different ways and both always return "0" in the log. However the correct size is always logged and all the data is there when the log comes from the ParserHandler.java class.

This is the accessor method in ParserHandler.java.

   public int getNumberofDogs(){
            return dogArray.size();
        }

I'd prefer to access the dogArray via accessor method (as this seems to be best practice from what I've gathered) however I'm open to all suggestions.

Thanks in advance!!

EDIT 8/23/12

I ended up solving the problem by declaring my ArrayLists Static . I know this (and public ) approach my not be ideal for OOP but i'm going with it. In my ParserHandler.java I declared

public static ArrayList<List1> dogArray = null; 
public static ArrayList<List1> otherArray = null;
public static ArrayList<List1> catArray = null;

Then begin my SAX parser:

@Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        if (qName.equalsIgnoreCase("ArrayOfDataFeedAnimal")){
            catArray = new ArrayList<List1>();
            dogArray = new ArrayList<List1>();
            otherArray = new ArrayList<List1>();
        }else if(qName.equalsIgnoreCase("DataFeedAnimal")){
            theList = new List1();
        }

then the rest of my SAX parsing stuff happens. Lastly, from whatever class I want to access the array i simply do that in the static way by ParserHandler.dogArray.size() to get the size of the array. I can now manipulate the array any way i see fit from whatever class i need to get it.

I'm still unclear why creating an instance of the ParserHandler class hasn't worked for me with my parsed ArrayLists because when it worked fine when I tested with a simple int[] .

hopefully this can help someone else in the future.

Thanks again for everyones feedback!

Cheers!

you can do it in two ways,

  1. Create a setter/getter class
  2. Make a public static method that returns ArrayList

First Method:

class name : myDataObject.java

private ArrayList myArrayList;

// setting the ArrayList Value 
public void setArrayList ( ArrayList myArrayList )
{
     this.myArrayList = myArrayList;
}

// getting the ArrayList value 
public ArrayList getArrayList() 
{
     return myArrayList;
}

Second Method:

In ArrayList file, ( suppose class name is class A.java )

private static ArrayList myArrayList = null; 

... 
// assign arraylist 

public static ArrayList getArrayList()
{
      return myArrayList;
}

in the calling activity/class you can call it using following code,

private ArrayList newArrayList = null;

newArrayList = A.getArrayList();

You should not make the Methods static.Because that is not an OOP Design then.

There are 2 ways:

1). Either make the properties public. (Not a good practise either)

2). add getters and setters for ParserHandler class

class ParserHandler {

  private  List<List1> dogArray = new ArrayList<List1>();

  public List<List1> getDogArray() {
   return this.dogArray;
  }

  public void setDogArray(List<List1> dogArray) {
    this.dogArray = dogArray;
  }


}

Now access dogArray Like this

ph.getDogArray();
 int m = ph.getDogArray().size();

Initially it will be 0 since it is an empty list. Use the setter method to set the array first

Note that in your oncreate you are doing a file operation in your ParserHandler which parses the xml file as your data. This could potentially block the UI thread if the ParserHandler is not processed in a separate thread. However if you processed in a separate thread then your int d = ph.getNumberofDogs(); may return 0 even if there are data in your xml because of race conditions between UI thread and the separate thread processing the parsing.

The best solution in my opinion is to create a listener when the parsing is done so that you are pretty sure that the processing is done before you access the size of the list.

add this in your ParserHandler class

class ParserHandler {

       ...... your original codes here

       private OnParsingDoneListener mListener;
       public void setOnParsingDoneListener (OnParsingDoneListener listener){
             mListener = listener;
       }

      public static interface OnParsingDoneListener {
            public void onParsingDone (List dogList);
      }

}

make sure to call mListener.onParsingDone when youre done parsing xml data.

In Your onCreate()...

ParserHandler ph = new ParserHandler();
ph.setOnParsingDoneListener (new ParserHandler.OnParsingDoneListener(){
     public void onParsingDone(List dogList){
         // do whatever you want to the doglist
         // at this point all parsing is done and dogList contains the data from xml
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM