Android - 使用另一个类的方法并不起作用

时间:2016-02-23 15:58:48

标签: java android class methods

在下面的代码中(为了使其更清晰,我剪了很多)我有一个活动,其中onCreate()调用方法getClothes()获取衣服列表的列表。然后第一件衣服装满了毕加索。

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);
}
}

我有二等的方法来获取衣服清单(文件数据类型列表)。

//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;
}}

这个版本的代码不起作用 - 应用程序开始运行。

但是,如果我将方法从第二类放入第一类(并且当然删除衣服myClothes对象) - 它可以工作!

为什么这个版本不起作用?

1 个答案:

答案 0 :(得分:1)

您没有实现myClothes对象的实例化。在调用其中的方法之前实例化它,它应该可以工作。

E.g。在您的活动中使用Clothes myClothes = new Clothes();

相关问题