Android Studio - 使用Parse.com将图像加载到网格视图

时间:2015-12-12 17:37:39

标签: android gridview parse-platform

我试图将图片(png)从Parse.com加载到我应用程序的一个片段中,而我得到的只是临时图像而不是我想要的图像。它可以工作,但它不会加载我想要的图像,它会加载临时图像。请帮忙! 这是我的代码:

更新:已修复。在应用程序中将图像加载到我的gridview。我必须编辑模拟器的SD卡大小和内部存储器才能工作。

    package ope.playingwithtabs;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.List;


public class TwoFragment extends Fragment{

    public TwoFragment() {
        // Required empty public constructor
    }


    GridView gridview;
    List<ParseObject> ob;
    ProgressDialog mProgressDialog;
    GridViewAdapter adapter;
    private List<GameList> gamearraylist = null;





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

        Parse.initialize(getContext());

        new RemoteDataTask().execute();



    }



    // RemoteDataTask AsyncTask
    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(getContext());
            // Set progressdialog title
            mProgressDialog.setTitle("Place Holder Title");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create the array
            gamearraylist = new ArrayList<GameList>();
            try {
                // Locate the class table named "GamesList" in Parse.com
                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                        "GamesList");
                // Locate the column named "position" in Parse.com and order list
                // by ascending
                query.orderByAscending("position");
                ob = query.find();
                for (ParseObject gameslist : ob) {
                    ParseFile image = (ParseFile) gameslist.get("games");
                    GameList map = new GameList();
                    map.setGame(image.getUrl());
                    gamearraylist.add(map);
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Locate the gridview in gridview_main.xml
            gridview = (GridView) getView().findViewById(R.id.gridView);

            // Pass the results into ListViewAdapter.java
            adapter = new GridViewAdapter(getContext(),
                    gamearraylist);
            // Binds the Adapter to the ListView
            gridview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }

Gridview布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="info.androidhive.materialtabs.fragments.OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RPG"
        android:textSize="40sp"
        android:textStyle="bold"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        android:id="@+id/textView" />

    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/gridView"
        android:layout_centerHorizontal="true"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:numColumns="3"
        android:verticalSpacing="4dp"
        android:padding="4dp"
        android:gravity="center"
        android:layout_below="@+id/textView" />





</RelativeLayout>

Gridview适配器

package ope.playingwithtabs;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ope on 12/12/2015.
 */
public class GridViewAdapter extends BaseAdapter{



    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ImageLoader imageLoader;
    private List<GameList> gamearraylist = null;
    private ArrayList<GameList> arraylist;

    public GridViewAdapter(Context context, List<GameList> gamearraylist) {
        this.context = context;
        this.gamearraylist = gamearraylist;
        inflater = LayoutInflater.from(context);
        this.arraylist = new ArrayList<GameList>();
        this.arraylist.addAll(gamearraylist);
        imageLoader = new ImageLoader(context);
    }

    public class ViewHolder {
        ImageView game;
    }

    @Override
    public int getCount() {
        return gamearraylist.size();
    }

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

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

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.gridview_item, null);
            // Locate the ImageView in gridview_item.xml
            holder.game = (ImageView) view.findViewById(R.id.game);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Load image into GridView
        imageLoader.DisplayImage(gamearraylist.get(position).getGame(),
                holder.game);
        // Capture GridView item click
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data phone
                intent.putExtra("game", gamearraylist.get(position)
                        .getGame());
                context.startActivity(intent);
            }
        });
        return view;
    }

ImageLoader的

public class ImageLoader {



    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.temp_img;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 100;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }



}

和logcat错误:

12-12 17:19:13.574 3629-3655/? I/MemoryCache: cache size=0 length=1
12-12 17:19:13.575 3629-3656/? W/System.err: java.io.FileNotFoundException: /storage/1AE7-3419/GamesParse/344698653: open failed: ENOENT (No such file or directory)
12-12 17:19:13.576 3629-3656/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:452)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
12-12 17:19:13.576 3629-3656/? W/System.err:     at ope.playingwithtabs.ImageLoader.getBitmap(ImageLoader.java:79)
12-12 17:19:13.576 3629-3656/? W/System.err:     at ope.playingwithtabs.ImageLoader.access$000(ImageLoader.java:27)
12-12 17:19:13.576 3629-3656/? W/System.err:     at ope.playingwithtabs.ImageLoader$PhotosLoader.run(ImageLoader.java:153)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-12 17:19:13.576 3629-3656/? W/System.err:     at java.lang.Thread.run(Thread.java:818)
12-12 17:19:13.576 3629-3656/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
12-12 17:19:13.576 3629-3656/? W/System.err:     at libcore.io.Posix.open(Native Method)
12-12 17:19:13.576 3629-3656/? W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
12-12 17:19:13.576 3629-3656/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:438)
12-12 17:19:13.576 3629-3656/? W/System.err:    ... 10 more

0 个答案:

没有答案