3

I have a custom class with the following code

public class BeerExpert {
public String[] getBrands(String color){
    String[] beer_brands= new String[2];
    if(color=="light") {
        beer_brands[0]="Budwiser";
        beer_brands[1]="Corona";
    }
    return beer_brands;

}
}

I want to import the list of array "beer_brands" in the other class, which is my mainActivity.java class. How ?

3 Answers3

0

If I understand correctly, you want to access beer_brands in another class.

In the other class, use the following (in any method):

BeerExpert be = new BeerExpert();
String[] beer_brands = be.getBrands("light");

All this does is create an instance of the class, and then call "getBrands()" using that instance.

0

If you are calling the getBrands() method directly from your MainActivity class then you just have to reference the array returned from the function in your MainActivity class. Here is how you can do it:

BeerExpert beerExpert = new BeerExpert();
String[] beer_brands = beerExpert.getBrands("light");

If you are not calling the getBrands() method from MainActivity class but from some other class and am only interested in the array declared in BeerActivity class then you'll have to declare it as static in your BeerExpert class:

public class BeerExpert {

    /* Public Static */
    public static String[] beer_brands = new String[2];

    public String[] getBrands(String color){

        if(color=="light") {
            beer_brands[0]="Budwiser";
            beer_brands[1]="Corona";
        }
        return beer_brands;

    }

}

You can then import it as follows in your MainActivity class:

String[] beer_brands = BeerExpert.beer_brands;
user2004685
  • 9,548
  • 5
  • 37
  • 54
0

1.Use equals(), compares the value equality means string values.

== compares object references.

    if(color.equals("light")) {
        beer_brands[0]="Budwiser";
        beer_brands[1]="Corona";
    }

Refrence: compare strings in java

2.To access beer_brands array in mainActivity class, just return the result from getBrands()method of BeerExpert class.

In mainActivity class,

BeerExpert be = new BeerExpert();
String[] beer_brands = be.getBrands("light");
Community
  • 1
  • 1
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31