如何通过凌空脱机加载图像。凌空是否自动缓存图像或需要缓存图像?

时间:2018-08-09 10:48:09

标签: android caching android-volley offline-caching

当我使用此api时:

private static final String JSON_URL = " https://simplifiedcoding.net/demos/view-flipper/heroes.php";


当断开互联网连接时显示了图像,因此不需要缓存;

我在try块中这样检索

JSONObject obj = new JSONObject(response);    
JSONArray teamArray = obj.getJSONArray("heroes"); 

但是当我使用这个api时:

private static final String JSON_URL = "   private static final String JSON_URL = "https://www.qasoftearth.com/images/team/team.json";

没有json对象,所以我在try块中这样检索,并且在断开互联网连接的情况下此图像未加载:

JSONArray teamArray=new JSONArray(response);

所以我想知道具有json对象的api和具有json数组的api有什么区别。拥有json对象会自动缓存图像吗?

下面是我的代码,当不存在Internet时如何加载图像?

OurTeam.java

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import com.avi_qasoftearth.aviqasoft.Adapter.OurTeamViewPagerAdapter;
    import com.avi_qasoftearth.aviqasoft.DataModel.Hero;
    import com.avi_qasoftearth.aviqasoft.DataModel.Team;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

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

    import me.relex.circleindicator.CircleIndicator;

    public class OurTeam extends AppCompatActivity {

        ViewPager viewPager;
        List<Team> our_team;
        TextView tv1,tv2;

        LinearLayout sliderDotspanel;
        int dotscount;
        ImageView[] dots;

        ArrayList<String>name_array= new ArrayList<>();
        ArrayList<String>img_url_array=new ArrayList<>();

  private static final String JSON_URL = "https://www.qasoftearth.com/images/team/team.json";
   // private static final String JSON_URL = " https://simplifiedcoding.net/demos/view-flipper/heroes.php";


        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.viewpager_our_team);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            tv1=(TextView) findViewById(R.id.our_team_name_textView);
            tv2=(TextView) findViewById(R.id.our_team_designation_textView);
            our_team=new ArrayList<>();
            loadTeam();


        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            onBackPressed();
            return super.onOptionsItemSelected(item);
        }

        private void loadTeam() {
            //getting the progressbar
            final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

            //making the progressbar visible
            progressBar.setVisibility(View.VISIBLE);

            //creating a string request to send request to the url
            StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
                    new Response.Listener<String>()
                    {
                        @Override
                        public void onResponse(String response) {
                            //hiding the progressbar after completion
                            progressBar.setVisibility(View.INVISIBLE);

                            Log.d("hello", response.toString());
                            try {

                                JSONArray teamArray=new JSONArray(response);


                                //now looping through all the elements of the json array
                                for (int i = 0; i < teamArray.length(); i++)
                                {
                                    //getting the json object of the particular index inside the array
                                    JSONObject teamObject = teamArray.getJSONObject(i);

                                    Team movie = new Team();
                                    movie.setEmpName(teamObject.getString("EmpName"));
                                    movie.setPic(teamObject.getString("Pic"));
                                    movie.setPosition(teamObject.getString("Position"));
                                    movie.setEmail(teamObject.getString("Email"));
                                    movie.setPhone(teamObject.getString("Phone"));
                                    our_team.add(movie);

                                }


                              viewPager = (ViewPager) findViewById(R.id.our_team_viewpager);
                              CircleIndicator indicator = (CircleIndicator)findViewById(R.id.indicator);
                              OurTeamViewPagerAdapter o=new OurTeamViewPagerAdapter(getApplicationContext(),our_team);
                              viewPager.setAdapter(o);

                              indicator.setViewPager(viewPager);


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

                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error)
                        {
                            //displaying the error in toast if occurrs
                            //Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                            Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
                        }
                    });


            AppController.getInstance().addToRequestQueue(stringRequest);


        }
    }

AppController.java

package com.avi_qasoftearth.aviqasoft;


import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private static AppController mInstance;
    private ImageLoader mImageLoader;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

LruBitmapCache.java

package com.avi_qasoftearth.aviqasoft;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
        ImageLoader.ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

3 个答案:

答案 0 :(得分:1)

改用滑行

RequestOptions options = new    RequestOptions() . centerCrop() ;
Glide.with(this).load(image_url).apply(options).into(imageView);

您可以通过以下方式缓存图像:

options.diskCacheStrategy(DiskCacheStrategy.SOURCE)

答案 1 :(得分:0)

我更喜欢使用Picasso太简单的图像库并缓存图像

      Picasso.with(context)
          .load("imgurl")
          .resize(80, 80)
          .error(R.drawable.user_dummy)
          .placeholder(R.drawable.user_dummy)
          .into(imageView);

答案 2 :(得分:0)

不,如果要缓存图像,则JSON对象和JSON数组在术语上没有区别。从程序员的角度来看,它们只是String直到被解析为止,因此Picasso只需要在load()中包含图像URL即可进行缓存它。

就您而言,我已经查看了您的API

  1. 在您的第一个API中,您将返回一个对象,其中图像的网址为 https://

  2. 在您的第二个API中,您正在使用 http://

这可能就是为什么您的图像未缓存的原因。