如何将URL路径转换为图像并显示在列表视图中

时间:2015-04-01 10:37:51

标签: android

根据我尝试搜索商店的位置,搜索结果显示在单元格的列表视图中。我从谷歌获得了名称,地址,相关的图标和评级,但问题是如何在列表单元格的列表视图中显示图像。我得到了Image的URL路径。我还将URL路径转换为bitmapImages使用Bitmap getBitmapFromURL()。但是它显示了NPE(Null POinter Exception)。下面我将粘贴代码。

public class NearByActivity extends Activity implements LocationListener
{
//    private ListAdapter adapter;
    ListView lvPlaces;
    ImageView ivPhone,ivCamera,ivPrinter,ivMore;
    String name,vicinity,formatted_phone_number,rating,icon;
    double mLatitude=0;
    double mLongitude=0;
    SharedPreferences spref;
    ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
//    CustomListAdapter customListAdapter;

    public ImageLoader imageLoader;


    private static final String Name = "name";
    private static final String Vicinity = "vicinity";
    private static final String Rating="rating";
    private static final String Icon="icon";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearby);

        lvPlaces=(ListView)findViewById(R.id.lvPlaces);


        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        lvPlaces.setAdapter(adapter);




        lvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> MainActivity, final View view,int position, long id)
            {

                final TextView tvVicinity=(TextView)view.findViewById(R.id.tvVicinity);
                final TextView tvRating=(TextView)view.findViewById(R.id.tvRating);
                final TextView tvName=(TextView)view.findViewById(R.id.tvName);
                final ImageView ivPhone = (ImageView)findViewById(R.id.ivPhone);
                final ImageView ivCamera = (ImageView)findViewById(R.id.ivCamera);
                final ImageView ivPrinter = (ImageView)findViewById(R.id.ivPrinter);
                final ImageView ivMore = (ImageView)findViewById(R.id.ivMore);

                ivPhone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        Toast.makeText(getApplication(),"Do you want the call",Toast.LENGTH_SHORT).show();
                    }
                });
                ivCamera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        Toast.makeText(getApplication(),"Do you want to take pics",Toast.LENGTH_SHORT).show();
                    }
                });
                ivPrinter.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        Toast.makeText(getApplication(),"Do you want to print",Toast.LENGTH_SHORT).show();
                    }
                });
                ivMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        Toast.makeText(getApplication(),"Do you want more",Toast.LENGTH_SHORT).show();
                    }
                });


                tvName.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        String getName=tvName.getText().toString();
                        String getVicinity=tvVicinity.getText().toString();
                        String getRating=tvRating.getText().toString();

                        Intent i = new Intent(getApplication(),Information.class);
                        i.putExtra(Name,getName);
                        i.putExtra(Vicinity,getVicinity);
                        i.putExtra(Rating,getRating);

                        startActivity(i);
                    }
                });
            }

        });

            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null)

            {
                onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider,20000,0,this);

            StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
            sb.append("location="+mLatitude+","+mLongitude);
            sb.append("&radius=1000");
            sb.append("&types=beauty_salon");
            sb.append("&sensor=true");
            sb.append("&key=AIzaSyBgtVo5lfnDQFY8W44TfMevgg2klgj5WeA");

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

            // Invokes the "doInBackground()" method of the class PlaceTask
            placesTask.execute(sb.toString());
        }

    /** A method to download json data from url */

    private String downloadUrl(String strUrl) throws IOException
    {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

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

            // Connecting to url
            urlConnection.connect();

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

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

            StringBuffer sb1  = new StringBuffer();

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

            br.close();

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

        return data;
    }

    @Override
    public void onLocationChanged(Location location)
    {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
    }

    @Override
    public void onProviderEnabled(String provider)
    {
    }

    @Override
    public void onProviderDisabled(String provider)
    {
    }

    public  Bitmap getBitmapFromURL(String icon ) {
        try {
            URL url = new URL(icon);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }




    private class PlacesTask 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)
        {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>
    {
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData)
        {
            JSONObject jObject;
            List<HashMap<String, String>> places = null;
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();
            try
            {
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);
            }
            catch(Exception e)
            {
                Log.d("Exception",e.toString());
            }
            return places;
        }
        @Override
        protected void onPostExecute(List<HashMap<String,String>> list)
        {
            for(int i=0;i<list.size();i++)
            {
                HashMap<String, String> hmPlace = list.get(i);
                name = hmPlace.get("place_name");
                vicinity = hmPlace.get("vicinity");
                rating=hmPlace.get("rating");
                formatted_phone_number = hmPlace.get("phone_number");
                icon = hmPlace.get("icon");
                placesListItems.add(hmPlace);

            }
            Toast.makeText(getApplication(),""+icon,Toast.LENGTH_SHORT).show();


            ImageView ivPics = (ImageView)findViewById(R.id.ivPics);
            ivPics.setImageBitmap(getBitmapFromURL(icon));



            ListAdapter adapter=new SimpleAdapter(NearByActivity.this,placesListItems,
                    R.layout.myplace,
                   new String[]{"place_name","vicinity","rating","phone_number"},
                   new int[]{R.id.tvName,R.id.tvVicinity,R.id.tvRating,R.id.ivPhone});
            lvPlaces.setAdapter(adapter);
        }

     }

logcat的:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
            at info.androidhive.slidingmenu.Activities.NearByActivity$ParserTask.onPostExecute(NearByActivity.java:328)
            at info.androidhive.slidingmenu.Activities.NearByActivity$ParserTask.onPostExecute(NearByActivity.java:289)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

2 个答案:

答案 0 :(得分:0)

试试这个

URL url = new URL("http://abcd.com/resize?sq=60&uid=2216744464");
Bitmap bmp =  BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

答案 1 :(得分:0)

您是否向manifest.xml添加了INTERNET权限

<uses-permission android:name="android.permission.INTERNET" /> 

更新1:

另外,你确定icon = hmPlace.get(“icon”);不是空的。

PS ivPics看起来很可疑。

更新2:

我猜的问题是ivPics,我认为它是空的。

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference