2014-11-09 196 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

相關問題