Java将图像从URL加载到Listview中

时间:2017-11-07 10:30:15

标签: android json listview url

现在3天之后,我觉得在接下来的3天没有结果之前,最好先问一下。

当前情况:我通过PHP API获取数据作为JSON。 数据是parsend,我现在有一个图像的URL作为?String?。 实际上,URL在Listview中显示为文本URL。

现在问题是如何在listView中显示图像?

使用以下代码,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);

所以我认为Problm是SimpleAdapter。 我还创建了一个这样的custon适配器:

    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;
        }

}

Full 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"
    />

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

干杯,迈克尔

修改 现在我修复了很多很多,感谢你们!#/ p>

解决方案:

 // 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 !!!!
            }

现在它的工作正常:)

1 个答案:

答案 0 :(得分:0)

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