在下面的代码中,当我在我的url变量中使用图片网址并将它们传递给我创建的适配器类时,piccasso将这些图像完美地渲染到gridview中。 getCurrentDetails()方法使用JsonObject和jsonArray从在线下载URL。返回的图像URL存储在全局变量mSmallImagesUrl中。但是当我将mSmallIMagesUrl作为我的适配器的参数传递时,piccasso不会渲染图像,它们是空白的。但是当我在url变量中使用硬编码的图像网址时,它可以正常工作。此外,mSmallImagesUrl将正确的图像网址打印到log cat中。所以我确信它不是一个pb,当从网上阅读图像网址时。请让我知道我做错了什么。谢谢。下面是代码
package com.paveynganpi.allsearch;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class ImageGrid extends ActionBarActivity {
private static final String TAG = ImageGrid.class.getSimpleName();
protected String mEditedString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Intent intent = getIntent();
mEditedString = intent.getStringExtra("space"); //contains the edited string
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_grid, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected GridView mGridView;//reference to gridview in fragment_image_grid.xml
protected int start = 4;//variable to change pages from google Api
//contains extra images urls to supply to ... when need
protected ArrayList<String> mBigImagesUrls = new ArrayList<String>();
//contains image urls to inject into gridview
protected ArrayList<String> mSmalImagesUrls = new ArrayList<String>();
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_grid, container, false);
String[] url = {
"http://i.telegraph.co.uk/multimedia/archive/02788/eden-hazard_2788463b.jpg",
"http://statsbomb.com/wp-content/uploads/2014/06/Eden-Hazard-1.jpg",
"http://i.telegraph.co.uk/multimedia/archive/02788/eden-hazard_2788463b.jpg",
"http://statsbomb.com/wp-content/uploads/2014/06/Eden-Hazard-1.jpg",
"http://i3.getwestlondon.co.uk/incoming/article6086661.ece/alternates/s2197/Eden-Hazard.jpg",
"http://fullfifa.com/wp-content/uploads/2014/11/arton10532.jpg",
"http://d.ibtimes.co.uk/en/full/1384908/eden-hazard.jpg",
"http://cdn.images.express.co.uk/img/dynamic/67/590x/16s118hazard1tSX-459966.jpg",
};
final ArrayList<String> testList = new ArrayList<String>();
Bundle args = getActivity().getIntent().getExtras();
String value= args.getString("space");
String imagesUrl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ value +"&rsz=8&start=" + start;
if(isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imagesUrl).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
for(int i =0;i<mSmalImagesUrls.size(); i++){
//Log.d(TAG,mSmalImagesUrls.get(i));
//testList.add(mSmalImagesUrls.get(i));
testList.add(mSmalImagesUrls.get(i));
}
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
}
else{
Toast.makeText(getActivity(), "Network is unavailable", Toast.LENGTH_LONG).show();
}
for(int i =0; i< url.length;i++){
//testList.add(mBigImagesUrls.get(i).trim());
testList.add(url[i]);
}
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
return rootView;
}
private ArrayList<String> getCurrentDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject responseData = jsonObject.getJSONObject("responseData");
ArrayList<String> localList = new ArrayList<String>();
JSONArray results = responseData.getJSONArray("results");
for(int i =0;i<results.length(); i++){
localList.add(results.getJSONObject(i).getString("url"));
}
return localList;
}
//An AlertDialog to display to user when an error occurs
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getActivity().getFragmentManager(),"error_dialog");
}
//checks if user is connected to a network
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if(activeNetwork != null && activeNetwork.isConnectedOrConnecting()){
isAvailable = true;
}
return isAvailable;
}
}
}
下面是我的适配器类
package com.paveynganpi.allsearch;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/ ** *由paveynganpi于2015年1月22日创建。 * / public class ImagesGridAdapter extends ArrayAdapter {
protected static final String TAG = ImagesGridAdapter.class.getSimpleName();
protected Context mContext;
protected ArrayList<String> mPicUrls;
public ImagesGridAdapter(Context context, ArrayList<String> picUrls) {
super(context, R.layout.images_view_grid_layout,picUrls);
mContext = context;
mPicUrls = picUrls;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.images_view_grid_layout,null);
holder = new ViewHolder();
holder.photoImageView = (ImageView)convertView.findViewById(R.id.googleImageView);
convertView.setTag(holder);//makes us return to initial state of listview after viewing the content
}
else{
holder =(ViewHolder)convertView.getTag();//gets the view holder that was already created
//if tag is no set as above, error will result due to the fact we are trying to retrieve a tag
//that is no longer available
}
//holder.authorImageView.setI(mTitle_authors.get(position).getAuthor());
Picasso.with(mContext).
load(mPicUrls.get(position))
.placeholder(R.drawable.ic_launcher)
.resize(300, 300)
.into(holder.photoImageView);
//Log.d(TAG,"title is ....." + mTitle_authors.get(0).getTitle());
return convertView;
}
public static class ViewHolder{
ImageView photoImageView;
}
}
我收到的json回复低于
{"responseData": {"results":[{"GsearchResultClass":"GimageSearch","width":"620","height":"387","imageId":"ANd9GcTFohFJ8qoz1khvOSGcs2ECNfM_07JslDbVwEFP9t2GCAaZa8pNc6DwE_Y","tbWidth":"136","tbHeight":"85","unescapedUrl":"http://i.telegraph.co.uk/multimedia/archive/02788/eden-hazard_2788463b.jpg","url":"http://i.telegraph.co.uk/multimedia/archive/02788/eden-hazard_2788463b.jpg","visibleUrl":"www.telegraph.co.uk","title":"Chelsea manager Jose Mourinho purrs at \u003cb\u003eEden Hazard\u003c/b\u003e progress \u003cb\u003e...\u003c/b\u003e","titleNoFormatting":"Chelsea manager Jose Mourinho purrs at Eden Hazard progress ...","originalContextUrl":"http://www.telegraph.co.uk/sport/football/teams/chelsea/10566887/Chelsea-manager-Jose-Mourinho-purrs-at-Eden-Hazard-progress-following-defeat-of-Hull-City-at-KC-Stadium.html","content":"\u003cb\u003eEden\u003c/b\u003e project: \u003cb\u003eEden Hazard\u003c/b\u003e","contentNoFormatting":"Eden project: Eden Hazard","tbUrl":"http://t2.gstatic.com/images?q\u003dtbn:ANd9GcTFohFJ8qoz1khvOSGcs2ECNfM_07JslDbVwEFP9t2GCAaZa8pNc6DwE_Y"},{"GsearchResultClass":"GimageSearch","width":"424","height":"594","imageId":"ANd9GcQxgNBlBEWTh0cW37JQFyybSEnKDxqRbRpPDBaIN0H5e0i670UlKIPl6LtK","tbWidth":"96","tbHeight":"135","unescapedUrl":"http://statsbomb.com/wp-content/uploads/2014/06/Eden-Hazard-1.jpg","url":"http://statsbomb.com/wp-content/uploads/2014/06/Eden-Hazard-1.jpg","visibleUrl":"statsbomb.com","title":"Gifolution: Five Years of Belgian Wizard \u003cb\u003eEden Hazard\u003c/b\u003e | StatsBomb","titleNoFormatting":"Gifolution: Five Years of Belgian Wizard Eden Hazard | StatsBomb","originalContextUrl":"http://statsbomb.com/2014/06/gifolution-five-years-of-belgian-wizard-eden-hazard/","content":"Belgian Wizard \u003cb\u003eEden Hazard\u003c/b\u003e","contentNoFormatting":"Belgian Wizard Eden Hazard","tbUrl":"http://t2.gstatic.com/images?q\u003dtbn:ANd9GcQxgNBlBEWTh0cW37JQFyybSEnKDxqRbRpPDBaIN0H5e0i670UlKIPl6LtK"},{"GsearchResultClass":"GimageSearch","width":"3600","height":"2502","imageId":"ANd9GcQ7yRG_Ba5H13m8EO0SbVI0APJ3saPSpv29Te_kYHNdjKxKk4NK_CdRnNOl","tbWidth":"150","tbHeight":"104","unescapedUrl":"https://nbcprosoccertalk.files.wordpress.com/2014/03/eden-hazard.jpeg","url":"https://nbcprosoccertalk.files.wordpress.com/2014/03/eden-hazard.jpeg","visibleUrl":"prosoccertalk.nbcsports.com","title":"\u003cb\u003eeden\u003c/b\u003e-\u003cb\u003ehazard\u003c/b\u003e.jpeg","titleNoFormatting":"eden-hazard.jpeg","originalContextUrl":"http://prosoccertalk.nbcsports.com/2014/03/05/eden-hazard-disputes-jose-mourinhos-claim-that-he-needs-rest/","content":"\u003cb\u003eeden\u003c/b\u003e-\u003cb\u003ehazard\u003c/b\u003e.jpeg","contentNoFormatting":"eden-hazard.jpeg","tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcQ7yRG_Ba5H13m8EO0SbVI0APJ3saPSpv29Te_kYHNdjKxKk4NK_CdRnNOl"},{"GsearchResultClass":"GimageSearch","width":"1416","height":"1963","imageId":"ANd9GcT_8mqEplfLMNFSLC72uF7WjyIFkLDKCi4yz8hAtdMwS2A22ULs1yFnAoo","tbWidth":"108","tbHeight":"150","unescapedUrl":"http://upload.wikimedia.org/wikipedia/commons/5/56/Eden_Hazard'13-14.JPG","url":"http://upload.wikimedia.org/wikipedia/commons/5/56/Eden_Hazard%2713-14.JPG","visibleUrl":"en.wikipedia.org","title":"\u003cb\u003eEden\u003c/b\u003e_\u003cb\u003eHazard\u003c/b\u003e\u0026#39;13-14.JPG","titleNoFormatting":"Eden_Hazard\u0026#39;13-14.JPG","originalContextUrl":"http://en.wikipedia.org/wiki/Eden_Hazard","content":"\u003cb\u003eHazard\u003c/b\u003e playing against","contentNoFormatting":"Hazard playing against","tbUrl":"http://t1.gstatic.com/images?q\u003dtbn:ANd9GcT_8mqEplfLMNFSLC72uF7WjyIFkLDKCi4yz8hAtdMwS2A22ULs1yFnAoo"},{"GsearchResultClass":"GimageSearch","width":"490","height":"348","imageId":"ANd9GcSgXIPdlU7XG6KYvq6-YHpCf_Bl6F2ugD5Vzoi9zYO095uZmXQsSbTXAZ8","tbWidth":"130","tbHeight":"92","unescapedUrl":"http://www.ronaldo7.net/news/2014/01/775-eden-hazard-playing-for-chelsea-in-premier-league.jpg","url":"http://www.ronaldo7.net/news/2014/01/775-eden-hazard-playing-for-chelsea-in-premier-league.jpg","visibleUrl
01-23 13:57:43.283 32249-32249 / com.paveynganpi.allsearch D / ImageGrid:0
答案 0 :(得分:0)
移动:
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
要:
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
//Move it here
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
mGridView.setAdapter(adapter);
}
});
...
因为您正在执行异步请求。请稍后考虑使用AsyncTask。