0

我正在编写一个目录应用程序,其中我正在使用此流程:

分类 > 产品 > 单品

能够获得包含完整详细信息的类别和产品列表,例如:名称、描述和价格。

但在这里我面临一个问题。我没有在 ListView 中获取图像。既不是类别也不是产品。请告诉我我在哪里失踪。我最近两天都在挣扎。

我正在使用 php 类来生成 JSON,并且我也在使用ImageLoaderFileCache和类。MemoryCacheUtils

CategoryActivity.java

public class CategoryActivity extends ListActivity {
    // Connection detector
    ConnectionDetector cd;
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    ArrayList<HashMap<String, String>> albumsList;
    // albums JSONArray
    JSONArray albums = null;
    // String imagepath;
    LazyAdapter adapter;
    // albums JSON url
    private static final String URL_ALBUMS = "http://^^^^.com/albums.php";
    // ALL JSON node names
    static final String TAG_ID = "id";
    static final String TAG_NAME = "name";
    static final String TAG_DESCRIPTION = "description";
    static final String TAG_IMAGEPATH = "imagepath";
    static final String TAG_SONGS_COUNT = "songs_count";
    public ImageLoader imageLoader;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        cd = new ConnectionDetector(getApplicationContext());
        // Check for internet connection
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(CategoryActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;

        }
        // Hashmap for ListView
        albumsList = new ArrayList<HashMap<String, String>>();
        // Loading Albums JSON in Background Thread
        new LoadCategories().execute();
        // get listview
        ListView lv = getListView();

        /**
         * Listview item click listener
         * TrackListActivity will be lauched by passing album id
         * */
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                long arg3) {
                // on selecting a single album
                // TrackListActivity will be launched to show tracks inside the album
                Intent i = new Intent(getApplicationContext(), ProductListActivity.class);
                // send album id to tracklist activity to get list of songs under that album
                String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
                i.putExtra("album_id", album_id);
                startActivity(i);
            }
        });
    }

    /**
     * Background Async Task to Load all Albums by making http request
     **/
    class LoadCategories extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         **/
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(CategoryActivity.this);
            pDialog.setMessage("Loading Please Wait ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting Albums JSON
         **/
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                    params);
            // Check your log cat for JSON reponse
            Log.d("Albums JSON: ", "> " + json);
            try {
                albums = new JSONArray(json);
                if (albums != null) {
                    // looping through All albums
                    for (int i = 0; i < albums.length(); i++) {
                        JSONObject c = albums.getJSONObject(i);

                        // Storing each json item values in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String description = c.getString(TAG_DESCRIPTION);
                        String image_url = c.getString(TAG_IMAGEPATH);
                        String songs_count = c.getString(TAG_SONGS_COUNT);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESCRIPTION, description);
                        map.put(TAG_IMAGEPATH,image_url);
                        map.put(TAG_SONGS_COUNT, songs_count);
                        // adding HashList to ArrayList
                        albumsList.add(map);
                    }
                }else{
                    Log.d("Albums: ", "null");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            /**
             * Updating parsed JSON data into ListView
             **/
            adapter = new LazyAdapter(
                    CategoryActivity.this, albumsList);
            // updating listview
            setListAdapter(adapter);
            // updating UI from Background Thread
            pDialog.dismiss();

        }
    }
}

LazyAdapter.java

public class LazyAdapter extends BaseAdapter {
    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_item_categories, null);
        TextView id = (TextView)vi.findViewById(R.id.album_id); 
        TextView title = (TextView)vi.findViewById(R.id.album_name); 
        TextView description = (TextView)vi.findViewById(R.id.album_description); 
        TextView cost = (TextView)vi.findViewById(R.id.songs_count); 
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); 

        HashMap<String, String> item = new HashMap<String, String>();
        item = data.get(position);

        // Setting all values in listview
        id.setText(item.get(CategoryActivity.TAG_ID));
        title.setText(item.get(CategoryActivity.TAG_NAME));
        description.setText(item.get(CategoryActivity.TAG_DESCRIPTION));
        cost.setText(item.get(CategoryActivity.TAG_SONGS_COUNT));
        imageLoader.DisplayImage(item.get(CategoryActivity.TAG_IMAGEPATH), thumb_image);
        return vi;
    }
}

albums.php

<?php
    /*
     * Simple JSON generation from static array
     * Author: JSR
     */

    include_once './data.php';
    $albums = array();

    // looping through each album
    foreach ($album_tracks as $album) {
        $tmp = array();
        $tmp["id"] = $album["id"];
        $tmp["name"] = $album["album"];
        $tmp["description"] = $album["detail"];
        $tmp["imagepath"] = $album["imageurl"];
        $tmp["songs_count"] = count($album["songs"]);

        // push album
        array_push($albums, $tmp);
    }

    // printing json
    echo json_encode($albums);
?>

data.php

<?php
    /*
     * Simple JSON generation from static array
     * Author: JSR
     */
    $album_tracks = array(
        1 => array(
            "id" => 1,
            "album" => "Appetizers",
            "detail" => "All appetizers served with mint and tamarind chutneys.",
            "imageurl" => "http://www.libpng.org/pub/png/img_png/pnglogo-blk-sml1.png",
            "songs" => array(
                array("id" => 1, "name" => "Achari Paneer", "description" => "Achari Paneer is flavorful, healthy and high in protein. Paneer is an Indian cheese, also known as chenna. Achari paneer is very versatile and can be served as an appetizer or as an accompaniment to a main course.", "imagepath" => "http://www.manjulaskitchen.com/blog/wp-content/uploads/asparagus_with_ginger-100x75.jpg", "duration" => "3.95")
            )
        )
    );
?>

ImageLoader.java

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 

    public ImageLoader(Context context){
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.ic_launcher;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if(bitmap != null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) 
    {
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if(b != null)
            return b;

        // from web
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while(true) {
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    // Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad = photoToLoad;
        }

        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            Activity a = (Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}
4

0 回答 0