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

标签 java android class methods

在下面的代码中(我删掉了很多代码以使其更清晰),我有一个 Activity,其中 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;
}}

此版本的代码不起作用 - 应用程序在启动时崩溃。

但是,如果我将第二类中的方法放入第一类中(当然并删除 Clothes myClothes 对象) - 它会起作用!

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

最佳答案

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

例如在您的 Activity 中使用 Clothes myClothes = new Clothes();

关于java - Android - 使用另一个类的方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582213/

相关文章:

java - 在 FOR 循环中初始化多个变量

java - 排序列表但不能直接比较两个模型

java - 在 Eclipse Indigo 中验证 JSF 标签/属性

android - 将推送通知接收到库项目中(lib 项目中的 Android C2DM)

vbscript - 是使用子类中的属性来访问父类更好,还是将父类公开更好?

c++ - 带/不带类的回调函数指针 C++

javascript - 如何提高 xPage 上的 typeAhead 性能?

android - TextSwitcher NullPointer 错误

android - 在 React Native 中隐藏 Android 导航栏

java - 如何在Java中创建可以代表两种不同类型的对象类型