有没有办法从JSON网址加载图片?

时间:2019-12-03 03:40:17

标签: java android

  

我无法通过JSON将图片加载到应用程序中。一世   可以加载所有内容,但缺少图片。

     

我更新了完整的文件,无论问题出在哪里,您都可以看到。   非常感谢

这是解析json数据的文件。正如一些建议所说,我尝试使用Glide。无法正常工作,因为我不知道glide.with(mcontext)->给我一个错误可以解析符号mcontext

包com.example.administrator.superclass.Activity_User;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.administrator.superclass.R;
import com.example.administrator.superclass.User_data;
import com.example.administrator.superclass.Utils.Exlist;
import com.example.administrator.superclass.Utils.Gridmanager;
import com.example.administrator.superclass.Utils.Okhttp_Util;
import com.example.administrator.superclass.Utils.ProgressDialog_Util;
import com.example.administrator.superclass.Utils.Toast_util;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class Home_home extends Fragment {
    private Banner homeBanner;
    private RecyclerView homeClassRecy;
    Handler handler = new Handler();
    Home_class_gs home_class_gs;

    Home_class_recy home_class_recy;

    Home_descovery_grid_recy home_descovery_grid_recy;
    Home_descovery_grid_gs home_descovery_grid_gs;
    RecyclerView homeDiscovery;
    List<Home_descovery_grid_gs> grid_gsList = new ArrayList<>();
    private RelativeLayout homeBookpl;
    SmartRefreshLayout smartRefreshLayout;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_home, null);
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        initView(view);

        return view;
    }


    private void initView(View view) {
        homeBookpl = (RelativeLayout) view.findViewById(R.id.home_bookpl);
        homeBanner = (Banner) view.findViewById(R.id.home_banner);
        homeClassRecy = (RecyclerView) view.findViewById(R.id.home_class_recy);
        homeBanner.setDelayTime(5000);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        homeClassRecy.setLayoutManager(layoutManager);
        homeDiscovery = view.findViewById(R.id.home_discovery);
        smartRefreshLayout=view.findViewById(R.id.home_smartre);
        Gridmanager gridmanager=new Gridmanager(getActivity(),2);
        gridmanager.setOrientation(LinearLayoutManager.VERTICAL);
        homeDiscovery.setLayoutManager(gridmanager);

        homeBookpl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),Places.class);
                startActivity(intent);
            }
        });

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
                refreshLayout.finishRefresh(2000);
            }
        });
    }

    private void initData() {
        final Loadbanner loadbanner = new Loadbanner();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String addata = Okhttp_Util.Ok_Get(getActivity(),"https://www.superclass.ltd/show_all_advertising.php");
                if (!addata.equals("")){
                    try {
                        JSONObject adjsonObject = new JSONObject(addata);
                        JSONArray adjsonArray = adjsonObject.getJSONArray("AD");
                        final List<String> list = new ArrayList<>();
                        for (int i = 0; i < adjsonArray.length(); i++) {
                            list.add((String) adjsonArray.get(i));
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                    homeBanner.setImageLoader(loadbanner);
                                    homeBanner.setImages(list).start();
                            }
                        });
                        initDescovery();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast_util.Toast_show(getActivity(),"网络似乎有问题!");

                        }
                    });
                }
            }
        }).start();
    }

    //轮播初始化
    private class Loadbanner extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            try {
                Glide.with(getActivity()).load(path).into(imageView);
            } catch (Exception e) {
                Log.e("轮播", e.toString());
            }
        }
    }

    //使用eventbus发送活动内容
    public class SetDiscoverydata {
        Home_descovery_grid_gs mapdata;
        int postion;
        public SetDiscoverydata(Home_descovery_grid_gs mapdata,int postion) {
            this.mapdata = mapdata;
            this.postion=postion;
        }
    }

    //使用eventbus发送课程内容
    public class Setcompanyclass {
        Home_class_gs companyclassdata;

        public Setcompanyclass(Home_class_gs companyclassdata) {
            this.companyclassdata = companyclassdata;
        }
    }

    private void initDescovery() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Home_class_gs> class_gsList = new ArrayList<>();
                String classdata = Okhttp_Util.Ok_Get(getActivity(),"https://www.superclass.ltd/show_fast_class.php");
                try {
                    JSONObject classjsonObject = new JSONObject(classdata);
                    JSONArray classjsonArray = classjsonObject.getJSONArray("fastclasses");
                    for (int i = 0; i < classjsonArray.length(); i++) {
                        JSONObject jsonObject1 = (JSONObject) classjsonArray.get(i);
                        home_class_gs = new Home_class_gs();
                        home_class_gs.setAddress(jsonObject1.getString("address"));
                        home_class_gs.setCompanyimage(jsonObject1.getString("companyimage"));
                        home_class_gs.setCompanyname(jsonObject1.getString("companyname"));
                        home_class_gs.setTypename(jsonObject1.getString("typename"));
                        home_class_gs.setImagepath(jsonObject1.getString("imagepath"));
                        home_class_gs.setStars(jsonObject1.getString("stars"));


                        String imagepath = jsonObject1.getString("imagepath");
                        String coming = jsonObject1.getString("companyimage");

                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                            Glide.with(mcontext).load(coming).into(home_class_gs);

                        }

                        if (!User_data.sxlist.isEmpty()){
                            if (User_data.sxlist.contains(home_class_gs.getTypename())){
                                class_gsList.add(home_class_gs);
                            }
                        }else {
                            class_gsList.add(home_class_gs);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        home_class_recy = new Home_class_recy(R.layout.item_home_class_recy, class_gsList);
                        homeClassRecy.setAdapter(home_class_recy);
                        home_class_recy.setEmptyView(R.layout.empty, homeClassRecy);
                        home_class_recy.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                EventBus.getDefault().postSticky(new Setcompanyclass(class_gsList.get(position)));
                                Intent intent = new Intent(getActivity(), Company_class.class);
                                startActivity(intent);
                            }
                        });
                    }
                });
                grid_gsList.clear();
                try {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("username", User_data.user);
                    String discovery = Okhttp_Util.Ok_Post(getActivity(),"https://www.superclass.ltd/show_discovery.php", hashMap);

                    JSONObject disjsonobj = new JSONObject(discovery);
                    JSONArray disjsonarr = disjsonobj.getJSONArray("actors");
                    for (int i = 0; i < disjsonarr.length(); i++) {
                        home_descovery_grid_gs = new Home_descovery_grid_gs();
                        JSONObject dis = (JSONObject) disjsonarr.get(i);
                        home_descovery_grid_gs.setId(dis.getString("discover_id"));
                        home_descovery_grid_gs.setTitle(dis.getString("title"));
                        home_descovery_grid_gs.setAddress(dis.getString("address"));
                        home_descovery_grid_gs.setDate(dis.getString("date"));
                        home_descovery_grid_gs.setWhatwedo(dis.getString("whatwedo"));
                        home_descovery_grid_gs.setWhatyouneed(dis.getString("whatyouneed"));
                        home_descovery_grid_gs.setWhocanjoin(dis.getString("whocanjoin"));
                        home_descovery_grid_gs.setImagepath(dis.getString("imagepath"));
                        home_descovery_grid_gs.setImage_path2(dis.getString("image_path2"));
                        home_descovery_grid_gs.setImage_path3(dis.getString("image_path3"));
                        home_descovery_grid_gs.setNumbers(dis.getString("numbers"));
                        home_descovery_grid_gs.setCompanyname(dis.getString("companyname"));
                        home_descovery_grid_gs.setTime(dis.getString("time"));
                        home_descovery_grid_gs.setLike(dis.getString("like"));
                        home_descovery_grid_gs.setPhone(dis.getString("phone"));
                        home_descovery_grid_gs.setWebsite(dis.getString("website"));
                        home_descovery_grid_gs.setCompanyimagepath(dis.getString("companyimagepath"));
                        home_descovery_grid_gs.setAboutus(dis.getString("aboutus"));
                        home_descovery_grid_gs.setType(dis.getString("type"));
                        home_descovery_grid_gs.setArea_name(dis.getString("area_name"));
                        Log.e("User_data.sxlist: ",User_data.sxlist.toString() );
                        if (!User_data.sxlist.isEmpty()){
                            if (User_data.sxlist.contains(home_descovery_grid_gs.getType())){
                                grid_gsList.add(home_descovery_grid_gs);
                                User_data.like_descovery.add(grid_gsList);
                            }
                        }else {
                            grid_gsList.add(home_descovery_grid_gs);
                            User_data.like_descovery.add(grid_gsList);
                        }
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            home_descovery_grid_recy=new Home_descovery_grid_recy(R.layout.item_home_discovery,grid_gsList);
                            homeDiscovery.setAdapter(home_descovery_grid_recy);
                            home_descovery_grid_recy.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    Intent intent=new Intent(getContext(),Home_discovery.class);
                                    startActivity(intent);
                                    EventBus.getDefault().postSticky(new SetDiscoverydata(grid_gsList.get(position),position));
                                }
                            });
                        }
                    });
                }catch (Exception e) {
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void GetF_Key(Filter.SendKey data){
        if (data.F_key.equals("init")){
            initDescovery();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deletlike(Like_descovery.Deletdeslike data){
        for (int i = 0; i < grid_gsList.size(); i++) {
            if (data.res.equals(grid_gsList.get(i).getId())){
                Log.e( "deletlike: ","a" );
                grid_gsList.get(i).setLike("0");
                home_descovery_grid_recy.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            initData();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用GlidePicasso

解析网址并加载图片-

String url = jsonObj.getString("imagepath")

Glide.with(mContext)
            .load(url)
            .into(imageView)

Picasso.get()
       .load(url)
       .into(holder.contImg)

答案 1 :(得分:1)

第一个同步gradle文件

implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.github.bumptech.glide:glide:4.10.0'

第二次将Internet权限放入AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

第三个也是最后一个定义毕加索或滑行以加载图像。

String comimg = home_class_gs.setImagepath(jsonObject1.getString("companyimage"));   
String imgpath = home_class_gs.setImagepath(jsonObject1.getString("imagepath"));

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
   Glide.with(mContext)
            .load(comimg)
            .into(imageView) //Sometime picasso dont load image below 5.0

   Glide.with(mContext)
            .load(imgpath)
            .into(imageView) //Sometime picasso dont load image below 5.0


}else{

Picasso.get()
       .load(comimg)
       .into(holder.contImg)

Picasso.get()
       .load(imgpath)
       .into(holder.contImg)
}