在BaseAdapter构造函数方法完成执行之前调用getCount()

时间:2016-05-10 05:45:13

标签: android json android-gridview baseadapter

我是android新手。我正在尝试创建一个GridView 由ImageView组成。图像来自flickr,我使用flickr API搜索flickr并接收JSON响应。我解析JSON数据以获取图像URL。 API调用和解析JSON数据在FlickrAdapter内完成,扩展了BaseAdapter。但问题是我的getView()方法永远不会被调用。我搜索了stackoverflow for this,我发现如果没有要显示的数据,则不会调用getView()。但我在FlickrAdapter构造函数中设置数据。我在方法中设置了一些调试文本,我看到在设置数据之前调用了getCount(),这意味着在FlickrAdapter构造函数完成执行之前调用getCount()。所以从不调用getView()。 我希望在我的FlickrAdapter的构造函数方法完成执行后调用getCount()方法。 我该如何解决这个问题?

这是我的BaseAdapter和其他类的代码

FlickrAdapter.java

public class FlickrAdapter extends BaseAdapter {

public ArrayList<FlickrImage> flickrImagesList;
private Context context;

public static  FlickrAdapter instance;
FlickrAdapter(final Context context, String searchText, Activity activity) {
    this.flickrImagesList = new ArrayList<FlickrImage>();
    this.context = context;
    instance = this;
    Flickr flickr = new Flickr(searchText, context, activity);
    //row[0] = inflater.inflate(R.layout.template, null, false);
    Log.d("URL", flickr.buildApiUrl());
    DownloadManager.getJsonResponse(flickr.buildApiUrl(), context, new VolleyCallBack<JSONObject>() {
        @Override
        public void onSuccess(JSONObject success) {
            //Log.d("JSON",success.toString());
            try {
                success = success.getJSONObject("photos");
                JSONArray photo = success.getJSONArray("photo");

                for (int i = 0; i < photo.length(); i++) {
                    JSONObject tempObject = photo.getJSONObject(i);
                    String result = new StringBuilder("https://farm" + tempObject.get("farm").toString() +
                            ".staticflickr.com/" +
                            tempObject.get("server").toString() +
                            "/" +
                            tempObject.get("id").toString() +
                            "_" +
                            tempObject.get("secret").toString() +
                            "_n.jpg").toString();

                    FlickrImage image = new FlickrImage(i, result);
                    instance.flickrImagesList.add(image);

                    Log.d("SIZE", String.valueOf(instance.flickrImagesList.size()));

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

@Override
public int getCount() {
    Log.d("COUNT",String.valueOf(flickrImagesList.size()));
    return flickrImagesList.size();
}

@Override
public Object getItem(int position) {
    return flickrImagesList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

class ViewHolder {
    ImageView myImage;

    ViewHolder(View v) {
        myImage = (ImageView) v.findViewById(R.id.individulaImage);
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.individual_image, parent, false);
        holder = new ViewHolder(row);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }


    FlickrImage tempImage = flickrImagesList.get(position);
    Log.d("Address", tempImage.imageName);

    //ImageView iv = (ImageView) convertView.findViewById(R.id.individulaImage);

    //Picasso.with(context).load(tempImage.imageName).into(iv);
    return row;
}}

Flickr.java

public class Flickr {
private StringBuilder urlBuilder = new StringBuilder("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e78808f6cf756218d6981fcdf8021f0c&tags=");
private String apiUrl = "";
private Context context = null;
private Activity activity;
private String[] individualImageUrl;
private String keyWord = "";

public Flickr(String keyWord, Context context, Activity activity) {
    this.keyWord=keyWord;
    this.apiUrl = buildApiUrl();
    this.context = context;
    this.activity = activity;
    //Log.d("APIURL", this.apiUrl);
}

public String buildApiUrl() {
    String[] temp;
    StringBuilder sb = new StringBuilder();
    temp = this.keyWord.split(" ");
    for (int i = 0; i < temp.length; i++) {
        sb.append(temp[i]);
        if (i != (temp.length - 1)) {
            sb.append("+");
        }
    }
    urlBuilder.append(sb);
    urlBuilder.append("&text=");
    urlBuilder.append(sb);
    urlBuilder.append("&format=json&nojsoncallback=1");

    return urlBuilder.toString();
}}

FlickrImage.java

public class FlickrImage {
public int imageId;
public String imageName;

FlickrImage(int imageId, String imageURL) {
    this.imageId = imageId;
    this.imageName = imageURL;
    }
}

VolleyCallBack.java

public interface VolleyCallBack<T> {
public void onSuccess(T success);
}

DownloadManager.java

public class DownloadManager {
public static void getJsonResponse(final String Url, Context context, final VolleyCallBack callBack) {
    JsonObjectRequest flickrJsonRequest = new JsonObjectRequest(Request.Method.GET, Url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    callBack.onSuccess(response);
                }
            },
            new Response.ErrorListener() {
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
    Volley.newRequestQueue(context).add(flickrJsonRequest);
}
}

1 个答案:

答案 0 :(得分:1)

在构造函数完成之前未调用它。您的Web代码在单独的线程中运行,因此您的构造函数代码完成,然后调用getCount。一旦您的Web代码完成,onSuccess就会被调用。

永远不建议在适配器中运行网络代码。在您的活动或片段中运行它,并在适配器上完成调用notifyDatasetChanged()后。