从另一个类(Android)中获取列表

时间:2015-06-15 14:13:33

标签: android arraylist

好的,我已经在这里搜索并尝试了解现有的问题,但很难,所以我发布了这个。 在我的应用程序卡中使用recyclerview显示。当用户单击任何项​​目时,其索引(int i)将传递给CardViewActivity,并显示与该值匹配的卡片。 我正在尝试从列表<>中显示卡片上的数据。如果我将它保存在同一个文件中,我没有任何问题。但是,我想将它保存在一个不同的公共文件中,并从其他类访问它。我当前的代码进入循环,我想我无法看到它究竟是什么。

请帮忙。

我的Person.class是:

class Person {
String name;
String age;
int photoId;
List<Person> persons;

Person(String name, String age, int photoId) {
    this.name = name;
    this.age = age;
    this.photoId = photoId;
}
protected void initializePerson(){
    persons = new ArrayList<>();
    persons.add(new Person("Emma Wilson", "23 years old", R.drawable.emma));
    persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.lavery));
    persons.add(new Person("Lillie Watts", "35 years old", R.drawable.lillie));
    CardViewActivity cardViewActivity = new CardViewActivity(persons, this);
    cardViewActivity.setDetails();

}
}

我正在尝试从CardViewActivity访问它:

public class CardViewActivity extends Activity {

TextView personName;
TextView personAge;
ImageView personPhoto;
List<Person> persons;
Person person;
int id;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    id = intent.getIntExtra("position", 0);
    Toast.makeText(this, "Message"+id, Toast.LENGTH_SHORT).show();
    //Person person = new Person();
    person.initializePerson();

    setContentView(R.layout.cardview_activity);
    personName = (TextView)findViewById(R.id.person_name);
    personAge = (TextView)findViewById(R.id.person_age);
    personPhoto = (ImageView)findViewById(R.id.person_photo);
    //personName.setText(persons.get(0).name);
    setDetails();

}

CardViewActivity(List<Person> persons, Person person){
    this.persons = persons;
    this.person = person;
}
public void setDetails(){
//this.persons = persons;
//Toast.makeText(this, "Inside setDetails() and id is "+i, Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Person name is "+persons.get(i).name, Toast.LENGTH_SHORT).show();
int i = id;
personName.setText(persons.get(i).name);
//personAge.setText(persons.get(i).age);
//personPhoto.setImageResource(persons.get(i).photoId);

}

private void initializeData(){
    persons = new ArrayList<>();
    persons.add(new Person("Emma Wilson", "23 years old", R.drawable.emma));
    persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.lavery));
    persons.add(new Person("Lillie Watts", "35 years old", R.drawable.lillie));


}
}

1 个答案:

答案 0 :(得分:0)

Do following

public class SomeConstant {
    public static List<String> someList = new ArrayList<String>();
    static {
        someList.add("John");
        someList.add("adam");
    }
}

//here you will call the list you created public class SomeClass {

    public static void main(String[] args) {
        System.out.println(SomeConstant.someList);
    }

}