【问题标题】:Java load image into Listview from URLJava 将图像从 URL 加载到 Listview
【发布时间】:2017-11-07 10:30:14
【问题描述】:

现在 3 天后,我认为最好在接下来的 3 天没有结果之前问清楚。

现状:我通过 PHP API 作为 JSON 获取数据。 数据已解析,我现在将图像的 URL 作为“字符串?”。 实际上 URL 在 Listview 中显示为文本 URL。

现在的问题是如何在 listView 中显示来自 URL 的图像?

使用以下代码,URL 在 listView 中显示为文本 - 这是有效的。

 ListAdapter adapter = new SimpleAdapter(this, mProductMapList, R.layout.list_product_categories,
                new String[] { KEY_ID, KEY_NAME, KEY_IMAGE},
               new int[] { R.id.id,R.id.name, R.id.image});
                new String[]{KEY_VER,KEY_NAME},new int[]{R.id.id,R.id.title});
       mListView.setAdapter(adapter);

所以我认为问题是 SimpleAdapter。 我还创建了一个这样的自定义适配器:

    ListView list= (ListView) this.findViewById(R.id.list_view);
    ListAdapter adapter =
            new MyAdapter(
                    this,
                    mProductMapList,
                    R.layout.list_product_categories,
                    new String[]{KEY_ID,KEY_NAME,KEY_IMAGE},
                    new int[]{R.id.id,R.id.name,R.id.image});
    list.setAdapter(adapter);

MyAdapter.java:

    package com.learn2crack.listviewjson;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

import com.squareup.picasso.Picasso;

import java.util.List;
import java.util.Map;

/**
 * Created by Michael on 07.11.2017.
 */

public class MyAdapter extends SimpleAdapter {
  //String KEY_IMAGE = "image";
        public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to){
            super(context, data, resource, from, to);
        }

        public View getView(int position, View convertView, ViewGroup parent){
            // here you let SimpleAdapter built the view normally.
            View v = super.getView(position, convertView, parent);

            // Then we get reference for Picasso
            ImageView img = (ImageView) v.getTag();
            if(img == null){
                img = (ImageView) v.findViewById(R.id.image);
                v.setTag(img); // <<< THIS LINE !!!!
            }
            // get the url from the data you passed to the `Map`
           // String url = ((Map)getItem(position)).get();
            // do Picasso
            Picasso.with(v.getContext()).load("http://copy-cat.at/wp-content/uploads/2014/06/as11.jpg").into(img);

            // return the view
            return v;
        }

}

完整 Shop.java(主)

    package com.learn2crack.listviewjson;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.learn2crack.listviewjson.model.AndroidVersion;
import com.learn2crack.listviewjson.model.ProductDetails;
import org.json.JSONObject;
import com.learn2crack.listviewjson.model.ResponseProduct;

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

import com.learn2crack.listviewjson.ImageAdapter;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

public class Shop extends AppCompatActivity implements LoadJSONTaskShop.listenerShop, AdapterView.OnItemClickListener {


    private ListView mListView;
    private Context context;
    ImageView imagee;
    public static final String URL = "http://copy-cat.at/api/?act=getProductCategories";
//http://copy-cat.at/api/?act=getProductCategories
    private List<HashMap<String, String>> mProductMapList = new ArrayList<>();

    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "title";
    private static final String KEY_IMAGE = "image";



    private Spinner spinner1, spinner2;
    private Button btnSubmit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        Log.e("TESTLOGSHOP", "SHOP");

        //instantiate your listView
       // ListView nameAndAgeListView = (ListView) findViewById(R.id.gridview);

//create your listView with your custom object
      //  ArrayList<ImageAdapter> nameAndAgeList = new ArrayList<>();

        mListView = (ListView) findViewById(R.id.list_view);
        ImageView imagee= (ImageView) findViewById(R.id.image); // your imageview onbject

       // context = this;
       // String imageUri = "https://i.imgur.com/tGbaZCY.jpg";
      //  ImageView ivBasicImage = (ImageView) findViewById(R.id.imagee);
        //Picasso.with(getApplicationContext()).load(imageUri).into(ivBasicImage);



        // ImageView imageView = (ImageView) findViewById(R.id.image);
        // Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

      // mListView.setOnItemClickListener(this);
       // mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          // @Override
           // public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
               // Intent i= new Intent(Shop.this,ShowProductDetails.class);
               //Sring itemString= mProductMapList.get(arg2).get(KEY_VER);
               // i.putExtra("productid",itemString);
               // Log.e("TESTLOG", itemString);

               // startActivity(i);
               // finish();
         //   }
     //   });
        new LoadJSONTaskShop(this).execute(URL);


        getCategories();

        addItemsOnSpinner2();
        addListenerOnButton();
        addListenerOnSpinnerItemSelection();

        String URL ="";
    // new LoadJSONTaskShop(this).execute(URL);

    }

    public void getCategories() {
        String URL ="";
        mListView = (ListView) findViewById(R.id.list_view);
       // new LoadJSONTaskShop(this).execute(URL);
    }



    // add items into spinner dynamically
    public void addItemsOnSpinner2() {

        spinner2 = (Spinner) findViewById(R.id.spinner2);

        String URL ="";
        //new LoadJSONTaskShop(this).execute(URL);



        List<String> list = new ArrayList<String>();
        list.add("list 1");
        list.add("list 2");
        list.add("list 3");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);
    }

    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    }

    // get the selected dropdown list value
    public void addListenerOnButton() {

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        btnSubmit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(Shop.this,
                        "OnClickListener : " +
                                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
                                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
                        Toast.LENGTH_SHORT).show();
            }

        });
    }

    public void onClick(View v) {
        startActivity(new Intent(this, Shop.class));
        finish();

    }
    ///////////
  //  @Override
    public void onLoaded(List<ProductDetails> productDetails) {

        for (ProductDetails android : productDetails) {

         //   HashMap<String, String> map = new HashMap<>();
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(KEY_ID, android.getId());
            map.put(KEY_NAME, android.getName());
            map.put(KEY_IMAGE, android.getImage());


           // new DownloadImage((ImageView) findViewById(R.id.image))
                  //  .execute("http://copy-cat.at/wp-content/uploads/2014/06/as11.jpg");

            String URL = "http://copy-cat.at/wp-content/uploads/2014/06/as11.jpg";
         //  new DownloadImage((ImageView) findViewById(R.id.imagee)).execute(URL);
          new DownloadImage();
           // Picasso.with(this).load("http://copy-cat.at/wp-content/uploads/2014/06/as11.jpg").into(imagee);
            Log.e("TESTLOGSHOPxx", android.getImage());

            mProductMapList.add(map);

        }

        loadListView();
    }

    @Override
    public void onError() {

        Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

       // Toast.makeText(this, mProductMapList.get(i).get(KEY_NAME),Toast.LENGTH_LONG).show();
        //ShowProduct.getProduct(this);
        Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
    }

    private void loadListView() {

        //ListAdapter adapter = new SimpleAdapter(this, mProductMapList, R.layout.list_product_categories,
               // new String[] { KEY_ID, KEY_NAME, KEY_IMAGE},
               // new int[] { R.id.id,R.id.name, R.id.image});
                //new String[]{KEY_VER,KEY_NAME},new int[]{R.id.id,R.id.title});
      // mListView.setAdapter(adapter);

        ListView list= (ListView) this.findViewById(R.id.list_view);
        ListAdapter adapter =
                new MyAdapter(
                        this,
                        mProductMapList,
                        R.layout.list_product_categories,
                        new String[]{KEY_ID,KEY_NAME,KEY_IMAGE},
                        new int[]{R.id.id,R.id.name,R.id.image});
        list.setAdapter(adapter);

    }


    // NAVIGATION
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }




}

错误:

java.lang.IllegalArgumentException: Target must not be null.
                                                                            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:607)
                                                                            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:590)
                                                                            at com.learn2crack.listviewjson.MyAdapter.getView(MyAdapter.java:37)

这里是 list_product_categories.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_vertical_margin">


<ImageView
    android:id="@+id/flag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/search"
    android:paddingTop="10dp"
    android:paddingRight="10dp"
    android:paddingBottom="10dp"
    />


<TextView
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        />


    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:textSize="20dp"
        android:textColor="#88000000"
        android:layout_weight="1"
        />

<ImageView
    android:id="@+id/imagee"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:textSize="20dp"
    android:textColor="#88000000"
    android:layout_weight="1"
    />

问题是什么? 您可以在代码中看到我测试了更多以设置显示图像但我是新手并且它并不那么容易...... 我希望你可以帮助我 :) 非常感谢!

干杯,迈克尔

编辑: 现在我已经修复了很多很多,非常感谢你们!

解决方案:

 // Then we get reference for Picasso
            ImageView img = (ImageView) v.findViewById(R.id.imagee);
            Log.e("", img.toString());
            if(img == null){
                img = (ImageView) v.findViewById(R.id.imagee);
                v.setTag(img); // <<< THIS LINE !!!!
            }

现在它工作正常:)

【问题讨论】:

  • 你检查过ImageView的id吗?在您复制粘贴的代码中,您在适配器中使用的是 imagee 而不是 image
  • 是的,我知道我已经检查过了。我将
  • 只需一步一步调试应用程序,我相信你会发现问题
  • ^ 就是这样。您的imgv.getContext()null。找出是哪一个,然后想办法确保它们不是null
  • 好的,谢谢...嗯,我是一个完全新手.. 没那么容易。我在没有结果的情况下搜索了大约 3 天的错误。其余的/方式还可以吗?那么我可以用这段代码在列表视图中显示图像吗?

标签: android json listview url


【解决方案1】:

您的img 变量为空(代码img = (ImageView) v.findViewById(R.id.image); 显然不能正常工作),因此它在抱怨。

【讨论】:

  • 好吧,但是我该如何解决呢?代码 MyAdapter 是来自网络的示例... :O
  • 基本上,我不知道静态 R 类中有什么(这是一个真的丑陋的类名称),但它似乎期望一个具有给定的组件标识符(可能存储在常量 R.id.image 中),但它没有找到它 - 可能是因为您已将其包含在您自己的视图中,但使用了不同的 ID(或没有指定的 ID)。
  • 抱歉,现在是另一个问题。 Url 是在 MyAdapter 中静态定义的。如何获取传递给 MyAdapter 的 URL? String url = ((Map)getItem(position)).get(KEY_IMAGE);不工作,KEY_IMAGE 为红色并给出错误 -.-
猜你喜欢
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2011-05-03
  • 1970-01-01
相关资源
最近更新 更多