通过 JSON 将背景图像填充到列表视图项中的问题

Posted

技术标签:

【中文标题】通过 JSON 将背景图像填充到列表视图项中的问题【英文标题】:Issues populating background image through JSON into list view items 【发布时间】:2014-09-12 16:22:39 【问题描述】:

我一直在尝试解决这个问题,但到目前为止我的尝试并不令人满意。

简而言之,我试图为从 JSON 数据生成的每个列表视图数组创建一个背景图像。我已经在 J​​SON 中设置了背景图像的 url。 JSON 函数已经配置好了,因此我已经能够从在线源将数据填充到应用程序中。

只是为了向您展示一个示例可视化。背景图像的显示类似于以下内容:

http://www.mobile-patterns.com/?q=Hotel+Tonight+feed

但每个背景图像项都将引用它们各自的 JSON 字符串。

我真的坚持这一点。提前致谢。

下面是我的 ListViewAdapter 类

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

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter 

    // Declare Variables

    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();
    protected String list_item_bac;

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) 
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    

    @Override
    public int getCount() 
        return data.size();
    

    @Override
    public Object getItem(int position) 
        return null;
    

    @Override
    public long getItemId(int position) 
        return 0;
    

    public View getView(final int position, View convertView, ViewGroup parent) 
        // Declare Variables
        TextView list_item_name;
        TextView country;
        TextView list_item_price;
        ImageView list_item_bac;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        RelativeLayout rootRelativeLayout=(RelativeLayout)itemView.findViewById(R.id.rootRelativeLayout);

        new ImageDownloadTask(rootRelativeLayout,"http://dooba.ca/analytics/ed.php").execute();
        //rootRelativeLayout.setBackground(null);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
        country = (TextView) itemView.findViewById(R.id.country);
        list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);

        // Locate the ImageView in listview_item.xml
        list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);

        // Capture position and set results to the TextViews
        list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
        country.setText(resultp.get(MainActivity.COUNTRY));
        list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View arg0) 
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);

                intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));

                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

                intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));

                intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
                // Start SingleItemView Class
                context.startActivity(intent);

            
        );
        return itemView;
    
    AsyncTask<View,View,View> mytask= new AsyncTask<View,View,View>() 

        @Override
        protected View doInBackground(View... params) 
                    Bitmap img = imageLoader.loadImageSync(list_item_bac);

            return null;
        
    ;

    class ImageDownloadTask extends AsyncTask<View, View, View>
    
        RelativeLayout mrelativelayout;
        String downloadUrl;
         Bitmap img;
        public ImageDownloadTask(RelativeLayout layout,String url)
        

            mrelativelayout=layout;
            downloadUrl=url;
        
        @Override
        protected View doInBackground(View... params) 
            // TODO Auto-generated method stub
            img = imageLoader.loadImageSync(downloadUrl);
            return null;
        
          protected void onPostExecute(Void result) 
                Drawable d = new BitmapDrawable(context.getResources(), img);
                mrelativelayout.setBackground(d);
            
    
    

下面是我的 JSON 函数类

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions 

    public static JSONObject getJSONfromURL(String url) 
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

         catch (Exception e) 
            Log.e("log_tag", "Error in http connection " + e.toString());
        

        // Convert response to string
        try 
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
                sb.append(line + "\n");
            
            is.close();
            result = sb.toString();
         catch (Exception e) 
            Log.e("log_tag", "Error converting result " + e.toString());
        

        try 

            jArray = new JSONObject(result);
         catch (JSONException e) 
            Log.e("log_tag", "Error parsing data " + e.toString());
        

        return jArray;
    

listview布局xml如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_ 
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="7dp"
android:id="@+id/rootRelativeLayout"
android:paddingBottom="7dp"
android:orientation="vertical" >
<TextView
    android:id="@+id/ranklabel"
    android:layout_
    android:layout_
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/list_item_name"
    android:layout_
    android:layout_
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/countrylabel"
    android:layout_
    android:layout_
    android:layout_below="@+id/ranklabel"
    android:text="@string/countrylabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/country"
    android:layout_
    android:layout_
    android:layout_below="@+id/list_item_name"
    android:layout_toRightOf="@+id/countrylabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/populationlabel"
    android:layout_
    android:layout_
    android:layout_below="@+id/countrylabel"
    android:text="@string/populationlabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/list_item_price"
    android:layout_
    android:layout_
    android:layout_below="@+id/country"
    android:shadowColor="#000000"
    android:shadowDx="-2"
    android:shadowDy="2"
    android:shadowRadius="0.01"
    android:textColor="#f2f2f2"/>

<ImageView
    android:id="@+id/list_item_bac"
    android:layout_alignParentTop="true"
    android:layout_
    android:layout_
    android:layout_margin="0dp"
    android:background="#000000"
    android:alpha="0.8" />
 </RelativeLayout>

如果您需要任何其他可以帮助您帮助我的信息,请告诉我。 任何帮助将不胜感激

单项点击更新代码

import java.util.ArrayList;

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

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dooba.beta.Events_List;
import com.dooba.beta.R;
import com.dooba.beta.R.id;
import com.dooba.beta.R.layout;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class EventsActivity extends Activity

    private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
    private GridView gvAnuncios;
    private ArrayList<Events_List> anuncios;
    private ArrayList<Events_List> items;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_anuncios);
        gvAnuncios = (GridView) findViewById(R.id.gridview_anuncios);
        anuncios = new ArrayList<Events_List>();
        //download JSON
        descargarAnuncios();

        //add interface ItemClickListener
        public interface ItemClickListener 


                listview.setOnItemClickListener(new OnItemClickListener()

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                        Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                        intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                        intent.putExtra("position", position); //order position in listview 0-1-2-3...
                        startActivity(intent); //start Activity
                    

                


                //catch in the second activity values ??that you use to
                long id_item = getIntent().getExtras().getLong("id_item");
                int position = getIntent().getExtras().getInt("id_item");

        //sorry, my english is low :)

        //remember add reference to id of the item from your json we service in adapter


            public long getItemId(int position) 
                return items.get(position).id; //<--your id from json

    
        





    public void descargarAnuncios()
        RequestQueue volley = Volley.newRequestQueue(this);
        JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
        volley.add(json);
    

    private Response.Listener<JSONObject> ResponseListener() 
        return new Response.Listener<JSONObject>() 
            @Override
            public void onResponse(JSONObject response) 
                try 
                    //your JSON Array
                    JSONArray array = response.getJSONArray("list_item");
                    for(int i = 0; i < array.length(); i++)
                        //add object anuncio to arraylist anuncios
                        anuncios.add(convertirAnuncio(array.getJSONObject(i)));
                    
                 catch (JSONException e) 
                    e.printStackTrace();
                
                gvAnuncios.setAdapter(new AdapterEvents(getApplicationContext(),anuncios));
                
            ;
        ;


    private Response.ErrorListener ErrorListener() 
        return new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error)  
        ;
    

    //object JSON
    private final Events_List convertirAnuncio(JSONObject obj) throws JSONException 
        long id = obj.getLong("id"); //id 
        String list_item_name = obj.getString("list_item_name"); //title item
        String list_item_description = obj.getString("list_item_description");
        String list_item_price = obj.getString("list_item_price");
        Uri uri = Uri.parse(obj.getString("list_item_bac")); //url image "http//:google.image.....jpg"
        return new Events_List(id,list_item_name,list_item_description,list_item_price, uri);
    

【问题讨论】:

【参考方案1】:

我做了与你类似的事情,并使用 Volley 和 Picasso 库解决了问题。这是我的代码,希望能帮到你。我用的是gridview,差不多。 https://mega.co.nz/#!3Z5SSTCR!PxG2SmPTFYwqY6RDfpU1RK8tS6hN9nBovGF8lCtUVoc

【讨论】:

非常感谢。它帮助很大。我现在正在研究“单项点击”。也就是说,当用户单击列表项时,它会为他们带来一个相应的活动,该活动会填充有关它的更多信息。 好的。检查这个...mega.co.nz/… 谢谢兄弟。您的支持令人难以置信。作为建议,我们可以尝试使用内存和文件等缓存来提高速度和效率,从而使用户体验更加无缝。以下链接提供了更多信息。 androidbegin.com/tutorial/…单品编码,请提供。我尝试添加它,但遇到了一些我难以修复的问题。您可以在我更新的帖子中查看带有单个项目的更新代码 您好,我对您的代码进行了改编,我在 android 4.4.2 上工作,仅导入和 Volley Picasso 库,然后运行。如有任何问题,我们在这里:)。注意:减小图像的大小,因为它会导致内存不足。 mega.co.nz/… 谢谢兄弟,你的帮助很大不能上传。至于您提出的新代码,我似乎更喜欢您以前的代码。问题在于根据您之前的建议添加单个项目,并将“添加接口 ItemClickListener”添加到活动中。我在我的初始帖子中添加了更新下的活动代码。如果单个项目中有一个按钮可以在单击时将用户带到新活动,那就太好了。

以上是关于通过 JSON 将背景图像填充到列表视图项中的问题的主要内容,如果未能解决你的问题,请参考以下文章

在列表视图项中动态设置图像视图很慢

如何将反序列化JSON中的列表传递给视图到选择列表

未将图像从 json 文件加载到我的列表视图

如何用图像作为背景填充 iOS 堆栈视图(UIStackView)?

通过 JSON 将图像数组加载到 tableview 图像视图中

在我的自定义列表项中单击书签图像的侦听器,多次更改另一个 row_item 图像