【问题标题】:Image not show in recyclerview from server图片未显示在服务器的 recyclerview 中
【发布时间】:2017-03-23 01:39:05
【问题描述】:

我按照本教程进行操作,但遇到了一些问题 (https://www.simplifiedcoding.net/android-recyclerview-and-cardview-tutorial/)。我有一张名为 images 的表,其中包含 id 和 images 列。

这是我的 getData.php

<?php 

    $sql = "SELECT * FROM images";

    require_once('dbConnect.php');

    $r = mysqli_query($con,$sql);

    $result = array(); 

    while($row = mysqli_fetch_array($r)){
        array_push($result,array(
        'name'=>$row['name'],
        'url'=>$row['image']
        ));
    }

    echo json_encode(array('result'=>$result));

    mysqli_close($con);

这是我的 config.java

package com.example.mdesigntemp;
import android.graphics.Bitmap;
public class ConfigChildItem {
public static String[] names;
public static String[] urls;
public static Bitmap[] bitmaps;

public static final String GET_URL = "http://www.kinandayu.com/image_content/getData.php";
public static final String TAG_IMAGE_URL = "url";
public static final String TAG_IMAGE_NAME = "name";
public static final String TAG_JSON_ARRAY="result";

public ConfigChildItem(int i){
    names = new String[i];
    urls = new String[i];
    bitmaps = new Bitmap[i];
    }
}

这是我的 recyclerviewAdapter :

public class RecyclerAdapter extends   RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

List<ListItem> items;

public RecyclerAdapter(String[] names, String[] urls, Bitmap[] images){
    super();
    items = new ArrayList<ListItem>();
    for(int i =0; i<names.length; i++){
        ListItem item = new ListItem();
        item.setName(names[i]);
        item.setUrl(urls[i]);
        item.setImage(images[i]);
        items.add(item);
    }
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).
            inflate(R.layout.item_list, parent, false);
    ViewHolder viewHolder = new ViewHolder(layoutView);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ListItem list =  items.get(position);
    holder.imageView.setImageBitmap(list.getImage());
    holder.textViewName.setText(list.getName());
    holder.textViewUrl.setText(list.getUrl());
}

@Override
public int getItemCount() {
    return items.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imageView;
    public TextView textViewName;
    public TextView textViewUrl;

    public ViewHolder(View itemView) {
        super(itemView);

        imageView = (ImageView) itemView.findViewById(R.id.items);
        textViewName = (TextView) itemView.findViewById(R.id.textViewTitle);
        textViewUrl = (TextView) itemView.findViewById(R.id.SimpleDescCardSub1);

    }
}
}

这是我的 childtab1 活动:

public class Child_Tab1 extends Activity{

private RecyclerView rvView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<String> dataSet;
private ConfigChildItem configchilditem;

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

    ActionBarTitleGravity();

    rvView = (RecyclerView) findViewById(R.id.rv1);

    rvView.setAdapter(adapter);
    rvView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    SpacesItemsDecoration decoration = new SpacesItemsDecoration(4);
    rvView.addItemDecoration(decoration);
    getData();
}

    private void ActionBarTitleGravity() {
        ActionBar actionbar = getActionBar();
        TextView textview = new TextView(getApplicationContext());
        LayoutParams layoutparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        textview.setLayoutParams(layoutparams);
        textview.setText("Kinandayu");
        textview.setTextColor(Color.parseColor("#00acc1"));
        textview.setGravity(Gravity.START);
        textview.setTextSize(20);
        actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionbar.setCustomView(textview);

}
    private void getData(){
        class GetData extends AsyncTask<Void,Void,String>{
            ProgressDialog progressDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = ProgressDialog.show(Child_Tab1.this, "Fetching Data", "Please wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                progressDialog.dismiss();
                parseJSON(s);
            }

            @Override
            protected String doInBackground(Void... params) {
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(ConfigChildItem.GET_URL);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                    }

                    return sb.toString().trim();

                }catch(Exception e){
                    return null;
                }
            }
        }
        GetData gd = new GetData();
        gd.execute();
    }

    public void showData() {
        adapter = new RecyclerAdapter(ConfigChildItem.names,ConfigChildItem.urls, ConfigChildItem.bitmaps);
        rvView.setAdapter(adapter);
    }

    private void parseJSON(String json){
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray array = jsonObject.getJSONArray(ConfigChildItem.TAG_JSON_ARRAY);

            configchilditem  = new ConfigChildItem(array.length());

            for(int i=0; i<array.length(); i++){
                JSONObject j = array.getJSONObject(i);
                ConfigChildItem.names[i] = getName(j);
                ConfigChildItem.urls[i] = getURL(j);
            }

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

        ChildItemListJSON gb = new ChildItemListJSON(this,this, ConfigChildItem.urls);
        gb.execute();
    }

    private String getName(JSONObject j){
        String name = null;
        try {
            name = j.getString(ConfigChildItem.TAG_IMAGE_NAME);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return name;
    }

    private String getURL(JSONObject j){
        String url = null;
        try {
            url = j.getString(ConfigChildItem.TAG_IMAGE_URL);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return url;
    }   
}

这是我的getbitmap:

public class ChildItemListJSON extends AsyncTask<Void,Void,Void> {

private Context context;
private String[] urls;
private ProgressDialog loading;
private Child_Tab1 child_Tab1;

public ChildItemListJSON(Context context, Child_Tab1 child_Tab1, String[] urls){
    this.context = context;
    this.urls = urls;
    this.child_Tab1 = child_Tab1;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    loading = ProgressDialog.show(context,"Downloading Image","Please wait...",false,false);
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    loading.dismiss();
    child_Tab1.showData();
}

@Override
protected Void doInBackground(Void... params) {
    for(int i=0; i<urls.length; i++){
        ConfigChildItem.bitmaps[i] = getImage(urls[i]);
    }
    return null;
}

private Bitmap getImage(String bitmapUrl){
    URL url;
    Bitmap image = null;
    try {
        url = new URL(bitmapUrl);
        image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    }catch(Exception e){}
    return image;
}
}

这是我的 listitem.java :

public class ListItem {
private String name;
private String url;
private Bitmap image;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public Bitmap getImage() {
    return image;
}

public void setImage(Bitmap image) {
    this.image = image;
}
}

我有一个包含 id 和 image 列的表 (varchar300)

我最大的问题是:

  1. 为什么我的数据库中的图片没有加载到我的 recylerview 中
  2. 我的 php 脚本做错了吗?我的图像存储在 cpanel 文件管理器中的文件夹上传中

任何答案对我都非常有帮助。提前致谢

【问题讨论】:

  • 您的图片网址不完整
  • @VivekMishra 我在哪里获取数据库中每个图像的 url?我是新手
  • 您只是从主文件夹保存图像路径。您还应该将基本 url 附加到图像路径
  • @VivekMishra 我认为这也是导致此问题的原因,但我不知道如何获得该教程中的特定网址。谁能帮我提供代码之类的解决方案?
  • 你的json响应中的url应该和教程中的一样

标签: php android sql image android-recyclerview


【解决方案1】:

使用 Glider Liberary 在 OnBindViewHolder 中显示来自服务器的图像

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ListItem list =  items.get(position);

    Glide.with(this)
         .load(list.getImage())
         .into(imageView);
    holder.textViewName.setText(list.getName());
    holder.textViewUrl.setText(list.getUrl());
}

在gradle中添加这个编译

compile 'com.github.bumptech.glide:glide:3.7.0'

【讨论】:

  • 我正在使用 eclipse,我没有 picasso 库,所以我使用此代码。我只有 glide 和 volley 库:(
  • 等待我正在更改我的和滑翔机支持库
  • 我在 Glide.with(this) 上收到此错误 The method with(Context) in the type Glide is not applicable for the arguments (RecyclerAdapter)....
  • getApplicationContext() 传入 Glide.with(getApplicationContext())
  • 它强迫我创建新方法getAplicationContext,那个方法的内容是什么?
猜你喜欢
  • 2021-03-17
  • 2020-06-24
  • 1970-01-01
  • 2015-09-04
  • 1970-01-01
  • 2017-07-07
  • 2020-07-02
相关资源
最近更新 更多