2014-11-09 257 views
0

我在服务器url中有图像,然后我传递并显示在卡片上。我已经在Android中使用LoaderImageView库完成了这个工作,并在Glass中显示,我将url链接传递给卡片。但我得到这个错误 “在类型CardBuilder的方法addImage(绘制对象)不适用的参数(字符串)”如何显示来自url的图像

代码:

public static Drawable drawableFromUrl(String url) { 
     Bitmap x; 


     try { 
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
      connection.connect(); 
      InputStream input = connection.getInputStream(); 

      x = BitmapFactory.decodeStream(input); 
      return new BitmapDrawable(x); 

      } catch(MalformedURLException e) { 
      //Do something with the exception. 
     } 

     catch(IOException ex) { 
      ex.printStackTrace(); 
     } 
     return null; 

    } 


    View view = new CardBuilder(getBaseContext(), CardBuilder.Layout.TITLE) 
    .setText("TITLE Card") 
    // .setIcon(R.drawable.ic_phone) 
    .addImage(drawableFromUrl(link)) 
    .getView(); 

回答

1

From the doc,addImage需要绘制对象,int或位图。它不需要String。

您可以使用AsyncTask或线程或任何您喜欢的方式下载图像并将其转换为Drawable。然后,你可以调用addImage。

例如:

// new DownloadImageTask().execute("your url...") 

private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {  
    protected Drawable doInBackground(String... urls) { 
     String url = urls[0]; 
     return drawableFromUrl(url); 
    } 

    protected void onPostExecute(Drawable result) { 
     // yourCardBuilder.addImage(link) 
     // or start another activity and use the image there... 
    } 
} 

public static Drawable drawableFromUrl(String url) throws IOException { 
    Bitmap x; 
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
    connection.connect(); 
    InputStream input = connection.getInputStream(); 
    x = BitmapFactory.decodeStream(input); 
    return new BitmapDrawable(x); 
} 

我没有测试的代码,但希望你的想法。

另见:

编辑:

private Drawable drawableFromUrl(String url) { 
    try { 
     Bitmap bitmap; 
     HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     bitmap = BitmapFactory.decodeStream(input); 
     return new BitmapDrawable(bitmap); 
    } catch (IOException e) { 
     return null; 
    } 
} 

private class DownloadImageTask extends AsyncTask<String, Void, Drawable> { 

    protected Drawable doInBackground(String... urls) { 
     String url = urls[0]; 
     return drawableFromUrl(url); 
    } 

    protected void onPostExecute(Drawable result) { 
     stopSlider(); 
     if(result != null) { 
      mCardAdapter.setCards(createCard(getBaseContext(), result)); 
      mCardAdapter.notifyDataSetChanged(); 
     } 
    } 
} 

查看my GitHub repo我的完整的例子。 SliderActivity可能对您有所帮助。

+0

获取未处理的异常类型IOException错误 – karthees 2014-11-09 15:22:50

+0

请检查我编辑的代码。仍然不工作.. – karthees 2014-11-09 15:30:29

+0

你可以查看我的编辑或查看GitHub上的完整示例。 – pt2121 2014-11-10 01:11:13

相关问题