如何获取数组中URL的位置?

时间:2014-09-10 14:09:00

标签: android arrays url gridview

我想要实现的目标是获取从Instagram收到的URL,并将其数组位置传递给网格视图中每个相应照片的onlick监听器。

这是我的代码:

MainActivity.java

public class MainActivity extends Activity {
private InstagramSession mInstagramSession;
private Instagram mInstagram;

private ProgressBar mLoadingPb;
private GridView mGridView;

private static final String CLIENT_ID = "83549f9eb76f4a5b90daf6e4e14da107";
private static final String CLIENT_SECRET = "6df26b0c8f664323a07126bfe8511651";
private static final String REDIRECT_URI = "http://www.yahoo.com";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mInstagram          = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

    mInstagramSession   = mInstagram.getSession();

    if (mInstagramSession.isActive()) {
        setContentView(R.layout.activity_user);

        InstagramUser instagramUser = mInstagramSession.getUser();

        mLoadingPb  = (ProgressBar) findViewById(R.id.pb_loading);
        mGridView   = (GridView) findViewById(R.id.gridView);

        ((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
        ((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);

        ((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mInstagramSession.reset();

                startActivity(new Intent(MainActivity.this, MainActivity.class));

                finish();
            }
        });

        ImageView userIv = (ImageView) findViewById(R.id.iv_user);

        DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_user)
                .showImageForEmptyUri(R.drawable.ic_user)
                .showImageOnFail(R.drawable.ic_user)
                .cacheInMemory(true)
                .cacheOnDisc(false)
                .considerExifParams(true)
                .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .writeDebugLogs()
                .defaultDisplayImageOptions(displayOptions)
                .build();

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);

        AnimateFirstDisplayListener animate  = new AnimateFirstDisplayListener();

        imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);

        new DownloadTask().execute();

    } else {
        setContentView(R.layout.activity_main);

        ((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mInstagram.authorize(mAuthListener);
            }
        });
    }
}

private void showToast(String text) {
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}

private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {
    @Override
    public void onSuccess(InstagramUser user) {
        finish();

        startActivity(new Intent(MainActivity.this, MainActivity.class));
    }

    @Override
    public void onError(String error) {
        showToast(error);
    }

    @Override
    public void onCancel() {
        showToast("OK. Maybe later?");

    }
};

public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

    static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        if (loadedImage != null) {
            ImageView imageView = (ImageView) view;
            boolean firstDisplay = !displayedImages.contains(imageUri);
            if (firstDisplay) {
                FadeInBitmapDisplayer.animate(imageView, 500);
                displayedImages.add(imageUri);
            }
        }
    }
}



ArrayList<String> photoList;



public class DownloadTask extends AsyncTask<URL, Integer, Long> {

    protected void onCancelled() {

    }

    protected void onPreExecute() {

    }

    protected Long doInBackground(URL... urls) {
        long result = 0;

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>(1);

            params.add(new BasicNameValuePair("count", "20"));

            InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
            String response          = request.createRequest("GET", "/users/21846697/media/recent", params);

            if (!response.equals("")) {
                JSONObject jsonObj  = (JSONObject) new JSONTokener(response).nextValue();
                JSONArray jsonData  = jsonObj.getJSONArray("data");

                int length = jsonData.length();

                if (length > 0) {
                    photoList = new ArrayList<String>();

                    for (int i = 0; i < length; i++) {
                        JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("standard_resolution");

                        photoList.add(jsonPhoto.getString("url"));

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

        return result;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(Long result) {
        mLoadingPb.setVisibility(View.GONE);

        if (photoList == null) {
            Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
        } else {
            DisplayMetrics dm = new DisplayMetrics();

            getWindowManager().getDefaultDisplay().getMetrics(dm);

            int width   = (int) Math.ceil((double) dm.widthPixels / 2);
            width=width-50;
            int height  = width;

            PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);

            adapter.setData(photoList);
            adapter.setLayoutParam(width, height);

           mGridView.setOnItemClickListener(new OnItemClickListener() {

                  @Override
                  public void onItemClick(AdapterView<?> parent, View view,
                                          int position, long id) {
                      // Maybe you'll have to cast it to a string, I'm currently writing directly in SO
                      String url = (String) parent.getAdapter().getItem(position);
                      Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", position);
                      startActivity(myintent);
                  }
              });

            mGridView.setAdapter(adapter);


        }
    }
}
}

PhotoListAdapter.java

public class PhotoListAdapter extends BaseAdapter {
private Context mContext;

private ImageLoader mImageLoader;
private AnimateFirstDisplayListener mAnimator;

private ArrayList<String> mPhotoList;

private int mWidth;
private int mHeight;

public PhotoListAdapter(Context context) {
    mContext = context;

    DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.instagram_logo)
            .showImageForEmptyUri(R.drawable.instagram_logo)
            .showImageOnFail(R.drawable.instagram_logo)
            .cacheInMemory(true)
            .cacheOnDisc(false)
            .considerExifParams(true)
            .build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            .writeDebugLogs()
            .defaultDisplayImageOptions(displayOptions)
            .build();

    mImageLoader = ImageLoader.getInstance();
    mImageLoader.init(config);

    mAnimator  = new AnimateFirstDisplayListener();
}

public void setData(ArrayList<String> data) {
    mPhotoList = data;
}

public void setLayoutParam(int width, int height) {
    mWidth  = width;
    mHeight = height;
}

@Override
public int getCount() {
    return (mPhotoList == null) ? 0 : mPhotoList.size();
}

@Override
public Object getItem(int position) {
    return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageIv;

    if (convertView == null) {
        imageIv = new ImageView(mContext);

        imageIv.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
        imageIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageIv.setPadding(0, 0, 0, 0);
    } else {
        imageIv = (ImageView) convertView;
    }

    mImageLoader.displayImage(mPhotoList.get(position), imageIv, mAnimator);

    return imageIv;
}
}

FullScreenImageView.java

        import android.app.Activity;

public class FullscreenImageView extends Activity {

String imageURL = getIntent().getStringExtra("SelectedImageURL");

}

1 个答案:

答案 0 :(得分:1)

你理解的gridView的工作流程是有一个适配器来填充这个视图。

我要做的是getItem(int position)返回一个URL,如果我很好理解,它将包含在你的mPhotoList中。类似的东西:

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

并在需要的地方使用它:

@Override
           public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // Maybe you'll have to cast it to a string, I'm currently writing directly in SO
                String url = parent.getAdapter().getItem(position)
                Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", url);
                startActivity(myintent);
            }
        });

希望它有所帮助。