Квадрат Пикассо не отображает изображения

В приведенном ниже коде, когда я использую URL-адреса изображений в моей переменной URL-адреса и передаю их классу адаптера, который я создал, piccasso отлично отображает эти изображения в представлении сетки. метод getCurrentDetails() загружает URL-адреса из Интернета, используя JsonObject и jsonArray. возвращаемые URL-адреса изображений хранятся в глобальной переменной mSmallImagesUrl. Но когда я передаю mSmallIMagesUrl в качестве параметра моего адаптера, piccasso не отображает изображения, они пусты. но когда я использую жестко запрограммированные URL-адреса изображений в переменной url, это работает. Кроме того, mSmallImagesUrl печатает правильные URL-адреса изображений в журнале cat. Поэтому я уверен, что это не pb при чтении URL-адресов изображений из Интернета. пожалуйста, дайте мне знать, что я делаю неправильно. Спасибо. Ниже приведен код

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 22.01.15. */ общедоступный класс ImagesGridAdapter расширяет 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


person user3137376    schedule 23.01.2015    source источник
comment
Можете ли вы опубликовать json, который вы получили?   -  person vinitius    schedule 23.01.2015
comment
@vinitius привет, я только что сделал, спасибо   -  person user3137376    schedule 23.01.2015
comment
Ваш код выглядит нормально. Возможно, Picasso не распознает ваш URL-адрес, так как uri, because load() также может использовать путь String. Попробуйте Uri.parse(mPicUrls.get(position)). Посмотрите, работает ли это   -  person vinitius    schedule 23.01.2015
comment
я просто понимаю, что моя переменная mSmallImagesUrl всегда выходит за рамки, я не знаю, почему, когда я вызываю getCurrentDetails, он показывает, что у меня есть 8 элементов в mSmallImagesUrl, но прежде чем я добавлю его в свой адаптер, он имеет размер 0. Я понятия не имею что здесь происходит.   -  person user3137376    schedule 23.01.2015
comment
Оооо, извините, что пропустил это. Вы делаете асинхронный запрос. Вы должны установить свой адаптер, когда получите ответ. Как сейчас, вы просто переходите к своему адаптеру new ArrayList<String>(), потому что ваш запрос еще не завершен   -  person vinitius    schedule 23.01.2015
comment
о, хорошо, спасибо, пожалуйста, не знаете ли вы какой-либо способ проверить, получил ли я ответ, потому что в моем методе постановки в очередь okhhp есть метод Onresponse(), я не знаю, об этом ли вы говорите   -  person user3137376    schedule 23.01.2015


Ответы (1)


Шаг:

 mGridView =(GridView) rootView.findViewById(R.id.imagesGrid);//reference to gridview
 ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(),mSmalImagesUrls);
 mGridView.setAdapter(adapter);

To:

 @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 позже.

person vinitius    schedule 23.01.2015
comment
при этом я получил эту ошибку: android.view.ViewRootImpl$CalledFromWrongThreadException: только исходный поток, создавший иерархию представлений, может касаться своих представлений. на com.paveynganpi.allsearch.ImageGrid$PlaceholderFragment$1.onResponse(ImageGrid.java:162). строка 162 — это mGridView.setAdapter(adapter); - person user3137376; 23.01.2015
comment
Отредактировал ответ, извините - person vinitius; 23.01.2015
comment
привет, @vinius, URL-адрес поиска изображений Google выглядит так: ajax.googleapis.com/ajax/services/search/, где параметр rsz в максимальном количестве изображений на странице и параметр start — это номер страницы. Я могу получить все изображения на странице. Но не знаю, как это сделать, скажем, для 20 страниц, то есть start = 0 ... 19. Мой код выше показывает, как я получил изображение со страницы. Пожалуйста, дайте мне знать, как я могу получить изображения для нескольких страниц. Я попытался использовать цикл for вне моей асинхронной задачи (okhttp enqueue). Спасибо. - person user3137376; 24.01.2015
comment
Эй, чувак, я предлагаю тебе открыть еще один вопрос, чтобы уточнить, чего именно ты хочешь :D - person vinitius; 24.01.2015
comment
спасибо, чувак, я сделал это здесь, stackoverflow.com/questions/28127078/ - person user3137376; 24.01.2015