如何在ListFragment中使用JSON获取图像?

时间:2014-11-14 05:59:27

标签: android json

我是android开发的新手,我使用JSON Parsing方法解析我的数据,我使用List Fragment扩展我的类,我希望我的数据在列表视图中,但问题是我得到的所有数据完全除了图像,我不知道如何解决它,我的回答看起来像这样

 {"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}

here is my logcat output see my output is look like this and i am not getting images

public class HomeFragment extends ListFragment {

    //CustomAdapter adapter;
    //private List<RowItem> rowItems;

    private ProgressDialog pDialog;
    //JSON parser class
    JSONParser jsonParser = new JSONParser();

    JSONArray matching=null;

    ArrayList<HashMap<String,String>> aList;
    private static String MATCH_URL = null;
    private static final String TAG_MATCH="matching";
    private static final String TAG_NAME="name";
    private static final String TAG_PROFILE="profile_id";
    private static final String TAG_IMAGE="image";
    private static final String TAG_CAST="cast";
    private static final String TAG_AGE="age";
    private static final String TAG_LOCATION="location";

    private ListView listview;

    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        String strtext = getArguments().getString("user_login_id");
         MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        aList = new ArrayList<HashMap<String,String>>();

       // rowItems = new ArrayList<RowItem>();

        listview=(ListView)rootView.findViewById(android.R.id.list);

        new LoadAlbums().execute();



        return rootView;
    }

    class LoadAlbums extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(HomeFragment.this.getActivity());
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected String doInBackground(String... args) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    matching = jsonObj.getJSONArray(TAG_MATCH);

                    // looping through All Contacts
                    for (int i = 0; i < matching.length(); i++) {
                        JSONObject c = matching.getJSONObject(i);

                        // Storing each json item values in variable
                        String user_name = c.getString(TAG_NAME);
                        String user_profile=c.getString(TAG_PROFILE);
                        String user_image=c.getString(TAG_IMAGE);
                        String user_cast=c.getString(TAG_CAST);
                        String user_age=c.getString(TAG_AGE);
                        String user_location=c.getString(TAG_LOCATION);



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

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME,user_name);
                        map.put(TAG_PROFILE, user_profile);
                        map.put(TAG_IMAGE, user_image);
                        map.put(TAG_CAST, user_cast);
                        map.put(TAG_AGE, user_age+" years");
                        map.put(TAG_LOCATION, user_location);



                        // adding HashList to ArrayList
                        aList.add(map);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }


        protected void onPostExecute(String file_url) {

            super.onPostExecute(file_url);
            // dismiss the dialog after getting all albums
            if (pDialog.isShowing())
            pDialog.dismiss();
            // updating UI from Background Thread

                    /**
                     * Updating parsed JSON data into ListView
                     * */

                    // updating listview

                   CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
                    setListAdapter(adapter);
                }

        }




}

5 个答案:

答案 0 :(得分:1)

尝试使用自定义适配器AndroidQuery

public class CustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<HashMap<String,String>> listData;
    private AQuery aQuery;

    private static final String TAG_NAME="name";
    private static final String TAG_PROFILE="profile_id";
    private static final String TAG_IMAGE="image";
    private static final String TAG_CAST="cast";
    private static final String TAG_AGE="age";
    private static final String TAG_LOCATION="location";


    public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
        this.context = context;
        this.listData=listData;
        aQuery = new AQuery(this.context);
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
            holder.propic = (ImageView) convertView.findViewById(R.id.propic);
            holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
            holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
            holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
            holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
            holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtproname.setText(listData.get(position).get(TAG_NAME));
        holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
        holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
        holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
        holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));

        aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);

        // image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
        return convertView;
    }
    class ViewHolder{
        ImageView propic;
        TextView txtproname;
        TextView txtproid;
        TextView txtprofilecast;
        TextView txtprofileage;
        TextView txtprofileplace;
    }
}

如何将适配器设置为ListView:

CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);

答案 1 :(得分:0)

您可以使用通用图像加载程序查看服务器中的图像.Z
只需传递图片网址和您的视图,就可以了。

此处提供的是Universal Image loader及其所有文档的链接 https://github.com/nostra13/Android-Universal-Image-Loader

跳它可以帮助你。

答案 2 :(得分:0)

我建议你不要使用Android Query。 Android本身给人以惊心动魄的api。您可以下载图像,下载位图或任何您想做的事情。 您可以从此处下载jar文件:here下载jar文件并将jar设置为Build Path。

AQuery androidAQuery=new AQuery(this);

作为直接从网址加载图片的示例:

androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

作为从url获取Bitmap的示例:

androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
                        @Override
                        public void callback(String url, Bitmap object, AjaxStatus status) {
                            super.callback(url, object, status);

                            //You will get Bitmap from object.
                        }

                    });

它非常快速和准确,使用它你可以在加载时找到更多功能,如动画;如果需要,获取位图;等

//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code



    private class EfficientAdapter extends BaseAdapter {

            private LayoutInflater mInflater;
            private Context context;

            public EfficientAdapter(Context context) {
                mInflater = LayoutInflater.from(context);
                this.context = context;
            }

            @Override
            public int getCount() {
                return aList.size();
            }

            @Override
            public Object getItem(int arg0) {
                return null;
            }

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

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {

                final ViewHolder holder;

                if (convertView == null) {
                    convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
                    holder = new ViewHolder();
                    holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
                    holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
                    holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
                    holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.txtName.setText(aList.get(position).get(TAG_NAME));
                holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
                holder.txtCast.setText(aList.get(position).get(TAG_CAST));
                holder.txtAge.setText(aList.get(position).get(TAG_AGE));
                aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
                return convertView;
            }

            class ViewHolder {
                TextView txtName;
                TextView txtProfile;
                TextView txtCast;
                TextView txtAge;
                ImageView imgUser;
            }

        }

答案 3 :(得分:0)

在SimpleAdapter的源代码中:

private void bindView(int position, View view) {
        final Map dataSet = mData.get(position);
        if (dataSet == null) {
            return;
        }

        final ViewBinder binder = mViewBinder;
        final String[] from = mFrom;
        final int[] to = mTo;
        final int count = to.length;

        for (int i = 0; i < count; i++) {
            final View v = view.findViewById(to[i]);
            if (v != null) {
                final Object data = dataSet.get(from[i]);
                String text = data == null ? "" : data.toString();
                if (text == null) {
                    text = "";
                }

                boolean bound = false;
                if (binder != null) {
                    bound = binder.setViewValue(v, data, text);
                }

                if (!bound) {
                    if (v instanceof Checkable) {
                        if (data instanceof Boolean) {
                            ((Checkable) v).setChecked((Boolean) data);
                        } else if (v instanceof TextView) {
                            // Note: keep the instanceof TextView check at the bottom of these
                            // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                            setViewText((TextView) v, text);
                        } else {
                            throw new IllegalStateException(v.getClass().getName() +
                                    " should be bound to a Boolean, not a " +
                                    (data == null ? "<unknown type>" : data.getClass()));
                        }
                    } else if (v instanceof TextView) {
                        // Note: keep the instanceof TextView check at the bottom of these
                        // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                        setViewText((TextView) v, text);
                    } else if (v instanceof ImageView) {
                        if (data instanceof Integer) {
                            setViewImage((ImageView) v, (Integer) data);                            
                        } else {
                            setViewImage((ImageView) v, text);
                        }
                    } else {
                        throw new IllegalStateException(v.getClass().getName() + " is not a " +
                                " view that can be bounds by this SimpleAdapter");
                    }
                }
            }
        }
    }

你可以看到你的视图是否是ImageView,代码将使用url String是resId in

/**
 * Called by bindView() to set the image for an ImageView but only if
 * there is no existing ViewBinder or if the existing ViewBinder cannot
 * handle binding to an ImageView.
 *
 * By default, the value will be treated as an image resource. If the
 * value cannot be used as an image resource, the value is used as an
 * image Uri.
 *
 * This method is called instead of {@link #setViewImage(ImageView, int)}
 * if the supplied data is not an int or Integer.
 *
 * @param v ImageView to receive an image
 * @param value the value retrieved from the data set
 *
 * @see #setViewImage(ImageView, int) 
 */
public void setViewImage(ImageView v, String value) {
    try {
        v.setImageResource(Integer.parseInt(value));
    } catch (NumberFormatException nfe) {
        v.setImageURI(Uri.parse(value));
    }
}

您的错误就在这里,因此您需要覆盖getView的{​​{1}}函数。以下是代码:

SimpleAdapter

答案 4 :(得分:0)

您需要创建适配器并将其扩展到BaseAdapter并添加所有项目并在AsyncTask方法中调用它,它将返回Haresh Chellana所说的输出。