简体   繁体   中英

Android - Using method from another class doesn't work

In a code below (I cut a lot of it to make it more clear) I have Activity which onCreate() calls method getClothes() which gets List of list of clothes. Then first clothes is loaded with picasso.

public class Act_ChooseClothes extends AppCompatActivity {

Clothes myClothes;//Second class

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choose_clothes_start);

    img_clothes_0 = (ImageView) findViewById(R.id.img_clothes);

    getClothes();//Calls method which gets List of lists of clothes

    Picasso.with(this).load(clothes_all_types.get(0).get(0)).into(clothes_0);//Picasso loads image from list of lists into ImageView
}

private void getClothes() {
    clothes_upper = new ArrayList<>();

    clothes_all_types = new ArrayList<List<File>>();//List of lists

    clothes_upper = myClothes.getList("Upper");//Gets list using second class's method

    clothes_all_types.add(clothes_upper);
}
}

I have second class's method which gets list of clothes (List of File data types).

//Second class which has "getList" method
public class Clothes{
 File dir = new File(Environment.getExternalStorageDirectory().toString(), "/Clothes/" ); //Direction to clothes

//This method gets paths of clothes and puts them into list (and then returns that list)
 public List<File> getList(String type){
    List<File> clothes = new ArrayList<>();

    File[] files=dir.listFiles();

    for (int i=0; i<files.length; i++)
    {
        File file = files[i];
        String filepath = file.getPath();
        if(filepath.contains(type)){
            clothes.add(file);
        }
    }
    return clothes;
}}

This version of code doesn't work - App falls on start.

However if I put method from second class into first class (and remove Clothes myClothes object of course) - it works!

Why this version doesn't work?

You're not instanciating your myClothes object. Instantiate it before calling a method in it and it should work.

Eg in your activity use Clothes myClothes = new Clothes();

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