Android:JSON Image下载不显示详细视图(但缩略图确实)

时间:2013-12-03 09:51:14

标签: json image parsing android-listview

我正在尝试提高应用程序性能下载缩略图以填充列表视图,然后,如果用户选择项目,则显示更大的分辨率图像。

想法是在listview上编写图像网址,并将值传递给详细活动,并在那里管理下载。

只使用一个图像,应用程序运行正常,但我不喜欢使用单个图像获得的结果。

在下面的代码中,添加的行前面有注释:

ListView显示所有带缩略图的项目

public class ListViewCategory extends Activity {

    private static final String TAG = "ListViewCategory: ";

    ListView mListView;
     String strUrl;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_category_layout);    


        // URL to the JSON data
        Intent iN = getIntent();
        Bundle b = iN.getExtras();
        if (b!=null){
            strUrl=(String)b.get("urlJSON");
        }


        // Creating a new non-ui thread task to download json data 
        DownloadTask downloadTask = new DownloadTask();

        // Starting the download process
        downloadTask.execute(strUrl);

        // Getting a reference to ListView of activity_main
        mListView = (ListView) findViewById(R.id.list);

    mListView.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                //get brand from listview
                TextView marcaDetail = (TextView) view.findViewById(R.id.marcas);
                String marcaToDetail = marcaDetail.getText().toString();

                //get model from listview
                TextView modeloDetail = (TextView) view.findViewById(R.id.modelos);
                String modeloToDetail = modeloDetail.getText().toString();

                //get photoUrl from listview
                TextView urlDetail = (TextView) view.findViewById(R.id.tvUrl);
                String urlToDetail = urlDetail.getText().toString();

                //get price from listview
                TextView priceDetail = (TextView) view.findViewById(R.id.precios);
                String priceToDetail = priceDetail.getText().toString();

                Intent iPosition = new Intent(view.getContext(),DetailViewItem.class);
                iPosition.putExtra("marca", marcaToDetail);
                iPosition.putExtra("photoDetail", urlToDetail);
                iPosition.putExtra("modelo", modeloToDetail);
                iPosition.putExtra("precio", priceToDetail);
                startActivity(iPosition);
                Toast.makeText(ListViewCategory.this,urlToDetail.toString() , Toast.LENGTH_LONG).show();
            }
    });

    }



    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                    sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }



    /** AsyncTask to download json data */
    private class DownloadTask extends AsyncTask<String, Integer, String>{
        String data = null;
                @Override
                protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);

                        }catch(Exception e){
                            Log.d("Background Task",e.toString());
                        }
                        return data;
                }

                @Override
                protected void onPostExecute(String result) {

                        // The parsing of the xml data is done in a non-ui thread 
                        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

                        // Start parsing xml data
                        listViewLoaderTask.execute(result);                        

                }
    }

    /** AsyncTask to parse json data and load ListView */
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        // Doing the parsing of xml data in a non-ui thread 
        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try{
                jObject = new JSONObject(strJson[0]);
                JSONParser jsonParser = new JSONParser();
                    jsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());
            }

            // Instantiating json parser class
            JSONParser jsonParser = new JSONParser();

            // A list object to store the parsed items list
            List<HashMap<String, Object>> brands = null;

            try{
                // Getting the parsed data as a List construct
                brands = jsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }          

            // Keys used in Hashmap 
            //added
            String[] from = { "foto","marca","modelo","precio","detail"};

            // Ids of views in list_v layout
            int[] to = { R.id.fotos,R.id.marcas,R.id.modelos,R.id.precios,R.id.tvUrl};

            // Instantiating an adapter to store each items
            // R.layout.list_v defines the layout of each item          
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), brands, R.layout.list_v, from, to);  

            return adapter;
        }

        /** Invoked by the Android on "doInBackground" is executed */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

            // Setting adapter for the listview
            mListView.setAdapter(adapter);

            for(int i=0;i<adapter.getCount();i++){
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
                String imgUrl = (String) hm.get("photoUrl");
                Log.i(TAG, imgUrl);
                ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("photoUrl",imgUrl);
                hm.put("position", i);

                // Starting ImageLoaderTask to download and populate image in the listview 
                imageLoaderTask.execute(hm);
            }
        }       
    }

    /** AsyncTask to download and load an image in ListView */
    private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

        @Override
        protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

            InputStream iStream=null;
            String imgUrl = (String) hm[0].get("photoUrl");
            int position = (Integer) hm[0].get("position");

            URL url;
            try {
                url = new URL(imgUrl);

                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url                
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                // Getting Caching directory 
                File cacheDirectory = getBaseContext().getCacheDir();

                // Temporary file to store the downloaded image 
                File tmpFile = new File(cacheDirectory.getPath() + "/lakari_"+position+".png");             

                // The FileOutputStream to the temporary file
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                // Creating a bitmap from the downloaded inputstream
                Bitmap b = BitmapFactory.decodeStream(iStream);             

                // Writing the bitmap to the temporary file as png file
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);              

                // Flush the FileOutputStream
                fOutStream.flush();

                //Close the FileOutputStream
                fOutStream.close();             

                // Create a hashmap object to store image path and its position in the listview
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

                // Storing the path to the temporary image file
                hmBitmap.put("foto",tmpFile.getPath());

                // Storing the position of the image in the listview
                hmBitmap.put("position",position);              

                // Returning the HashMap object containing the image path and position
                return hmBitmap;                


            }catch (Exception e) {              
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            // Getting the path to the downloaded image
            String path = (String) result.get("foto");          

            // Getting the position of the downloaded image
            int position = (Integer) result.get("position");

            // Getting adapter of the listview
            SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

            // Getting the hashmap object at the specified position of the listview
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);   

            // Overwriting the existing path in the adapter 
            hm.put("foto",path);

            // Noticing listview about the dataset changes
            adapter.notifyDataSetChanged(); 

        }
    }

}

ListViewCategory布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ListViewCategory" 
    android:background="#000000">
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

    </TextView>


    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#e600e6"
        android:dividerHeight="0.2sp"/>
</RelativeLayout>

ListView单元格:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1" 
        android:orientation="vertical"
        android:background="#a8a8a8" >

        <ImageView
            android:id="@+id/fotos"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:contentDescription="@string/description"
            android:src="@drawable/ic_launcher" />
        <!--  
         <TextView
            android:id="@+id/tvUrl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#aaaaaa" 
            android:textSize="6sp"/>
            -->

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2" >
      <TextView
            android:id="@+id/tvUrl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#aaaaaa" 
            android:textSize="12sp"/>
     <TextView
        android:id="@+id/marcas"
        android:textSize="14sp"
        android:textColor="#aaaaaa"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        />   

    <TextView
        android:id="@+id/modelos"
        android:textSize="22sp"
        android:textColor="#e600e6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        />

    <TextView
        android:id="@+id/precios"
        android:textSize="16sp"
        android:textColor="#aaaaab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        />

    </LinearLayout>

</LinearLayout>

JSON解析器:

/** A class to parse json data */
public class JSONParser {

    // Receives a JSONObject and returns a list
    public List<HashMap<String,Object>> parse(JSONObject jObject){      

        JSONArray jItems = null;
        try {       
            // Retrieves all the elements in the "items" array 
            jItems = jObject.getJSONArray("items");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return getItems(jItems);
    }

    private List<HashMap<String, Object>> getItems(JSONArray jItems){
        int itemCount = jItems.length();
        List<HashMap<String, Object>> itemList = new ArrayList<HashMap<String,Object>>();
        HashMap<String, Object> item = null;    

        // Taking each item, parses and adds to list object 
        for(int i=0; i<itemCount;i++){
            try {
                // Call getItem with item JSON object to parse the item 
                item = getItem((JSONObject)jItems.get(i));
                itemList.add(item);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return itemList;
    }

    // Parsing the JSON object 
    private HashMap<String, Object> getItem(JSONObject jItem){

        HashMap<String, Object> item = new HashMap<String, Object>();
        String marca = "";
        String foto = "";
        String modelo = "";
        String precio = "";
        //añadido
        String detail = "";


        try {
            marca = jItem.getString("marca");
            foto = jItem.getString("photoUrl");
            modelo = jItem.getString("modelo");
            precio = jItem.getString("precio");
            //added
            detail = jItem.getString("photoDetail");

            item.put("marca", marca);
            item.put("foto", R.drawable.ic_launcher);
            item.put("modelo", modelo);
            item.put("photoUrl", foto);
            item.put("precio", precio);
            //added
            item.put("photoDetail", detail);

        } catch (JSONException e) {         
            e.printStackTrace();
        }       
        return item;
    }
}

最后,细节活动我错误,没有图像,但应用程序没有崩溃:

public class DetailViewItem extends Activity{
    //added
    ImageView imageView;

    private String photoCacheUri = "";
    private String detailMarca = "";
    private String detailModelo = "";
    private String detailPrecio = "";
    private String mailBody = "";
    private String mailSubject = "";
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.detail_view_item_layout);
            Intent intentDetail = getIntent();
            Bundle bDetail = intentDetail.getExtras();
            if (bDetail != null){
                detailMarca = (String)bDetail.get("marca");
                photoCacheUri = (String)bDetail.get("photoDetail");
                detailModelo = (String)bDetail.getString("modelo");
                detailPrecio = (String)bDetail.getString("precio");
            }

            //set brand
            TextView textviewMarca = (TextView) findViewById(R.id.tvMarca);
            textviewMarca.setText(detailMarca);
            //set image
            /*ImageView imageView = (ImageView) findViewById(R.id.photoDetail);
            Bitmap bmImg = BitmapFactory.decodeFile(photoCacheUri);
            imageView.setImageBitmap(bmImg);*/
            //added
            imageView= (ImageView) findViewById(R.id.photoDetail);
            // Create an object for subclass of AsyncTask
            GetXMLTask task = new GetXMLTask();
            // Execute the task
            task.execute(new String[] { photoCacheUri });


            //set model
            TextView textviewModelo = (TextView) findViewById(R.id.tvModelo);
            textviewModelo.setText(detailModelo);

            //set price
            TextView textviewPrecio = (TextView) findViewById(R.id.tvPrecio);
            textviewPrecio.setText(detailPrecio);

           }
     //added
     private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... urls) {
                Bitmap map = null;
                for (String url : urls) {
                    map = downloadImage(url);
                }
                return map;
            }

            // Sets the Bitmap returned by doInBackground
            @Override
            protected void onPostExecute(Bitmap result) {
                imageView.setImageBitmap(result);
            }

            // Creates Bitmap from InputStream and returns it
            private Bitmap downloadImage(String url) {
                Bitmap bitmap = null;
                InputStream stream = null;
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                bmOptions.inSampleSize = 1;

                try {
                    stream = getHttpConnection(url);
                    bitmap = BitmapFactory.
                            decodeStream(stream, null, bmOptions);
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return bitmap;
            }

            // Makes HttpURLConnection and returns InputStream
            private InputStream getHttpConnection(String urlString)
                    throws IOException {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();

                try {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    httpConnection.setRequestMethod("GET");
                    httpConnection.connect();

                    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        stream = httpConnection.getInputStream();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return stream;
            }
        }

}

logcat的:

  12-03 04:33:12.256: W/System.err(2420): java.net.MalformedURLException: Protocol not found: 
    12-03 04:33:12.256: W/System.err(2420):     at java.net.URL.<init>(URL.java:178)
    12-03 04:33:12.266: W/System.err(2420):     at java.net.URL.<init>(URL.java:127)
    12-03 04:33:12.276: W/System.err(2420):     at com.lupradoa.lakari.fragmenttabstudy.tabB.DetailViewItem$GetXMLTask.getHttpConnection(DetailViewItem.java:131)
    12-03 04:33:12.276: W/System.err(2420):     at com.lupradoa.lakari.fragmenttabstudy.tabB.DetailViewItem$GetXMLTask.downloadImage(DetailViewItem.java:117)
    12-03 04:33:12.276: W/System.err(2420):     at com.lupradoa.lakari.fragmenttabstudy.tabB.DetailViewItem$GetXMLTask.doInBackground(DetailViewItem.java:98)
    12-03 04:33:12.276: W/System.err(2420):     at com.lupradoa.lakari.fragmenttabstudy.tabB.DetailViewItem$GetXMLTask.doInBackground(DetailViewItem.java:1)
    12-03 04:33:12.276: W/System.err(2420):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
    12-03 04:33:12.276: W/System.err(2420):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    12-03 04:33:12.326: W/System.err(2420):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    12-03 04:33:12.326: W/System.err(2420):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    12-03 04:33:12.326: W/System.err(2420):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    12-03 04:33:12.346: W/System.err(2420):     at java.lang.Thread.run(Thread.java:841)
    12-03 04:33:12.496: W/EGL_emulation(2420): eglSurfaceAttrib not implemented

我已经修改了很多次代码,但我找不到错误。你们有人能指出来吗?

0 个答案:

没有答案