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