我想将我的API结果存储在数组列表中,需要存储,ID和ImageURL。 我可以使用我的ImgModel类存储数据。但我以后无法弄清楚如何访问它。
public class ImgModel{
private String url, id;
public ImgModel(String id, String url) {
this.id = id;
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getId() {
return id;
}
public void setId(String photoId) {
this.id = photoId;
}
}
在MainActivity中我称之为API
public class MainActivity ....{
...
List<ImgModel> photosList = new ArrayList<ImgModel>();
....
//>>in the result API... after parse the json
String id = imgOgj.getString("id");
String url = imgOgj.getString("url");
ImgModelp p = new ImgModel(id, url);
photosList.add(p); //THIS WORKS
}
本部分我不知道如何实施 - 请帮助
现在,在ImagePreview活动中,我想要访问这些图像,并且ID将显示在图像视图中。
public class ImagePreviewActivity ....{
//List<ImgModel> mProcessedImg= new ArrayList<ImgModel>(); //If I do this, that means I am creating a new list, and not accessing the store data right ?
ProcessedImg mProcessedImg;
ImageView mImageView;
onCreate{
....
mProcessedImg.size(); //Get the size .i.e how make images url
mImageView.setImage(mProcessedImg.getUrl(0);//sample how can I get the url of position 0 ?
}
}
答案 0 :(得分:1)
您在MainActivity中声明的photosList变量是local variable,这意味着它的范围仅限于声明它的代码块。这就是您无法访问代码中其他位置存储在该变量中的数据的原因。
为了在声明它的代码块之外再次使用和访问同一个变量,您可以改为使用MainActivity类的实例变量,修改类声明,如下所示:
public class MainActivity extends Activity {
List<ImgModel> mPhotosList;
...
// Override the OnCreate method of Activity
@Override
public void onCreate(Bundle savedInstanceState) {
// Create the mPhotosList instance variable
mPhotosList = new ArrayList<ImgModel>;
...
}
// other methods where you call the API and store the data in mPhotosList
...
}
这些页面可能有助于解释您可以在Java中使用的变量类型之间的差异:
what is the difference between local and instance variables in Java
http://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
就问题的下一部分而言,要从另一个Activity访问mPhotosList成员变量,以下帖子可能有所帮助:
答案 1 :(得分:0)
如果您需要在许多活动之间共享列表,那么将其放入MyApp的实例可能是一种解决方案。
答案 2 :(得分:0)
在ImagePreviewActivity.class
中创建允许一个List参数的构造函数。
public class ImagePreviewActivity ....{
List<ImgModel> imgList;
ImageView mImageView;
public ImagePreviewActivity(List<ImgModel> imageList){
this.imgList = imageList;
}
onCreate{
mImageView.setImage(imageList.get(0).getUrl();
}
}
创建ImagePreviewActivity.class
public class MainActivity ....{
...
List<ImgModel> photosList = new ArrayList<ImgModel>();
....
String id = imgOgj.getString("id");
String url = imgOgj.getString("url");
ImgModelp p = new ImgModel(id, url);
photosList.add(p);
//Craeate Object of ImagePreviewActivity
ImagePreviewActivity ipa = new ImagePreviewActivity(photosList);
}