2017-08-28 66 views
0

我有一個有Bitmap對象的類,並且當我將FireValue(MyClass.class)設置爲FirebaseDatabase時,我發現這是可能的! RealtimeDatabase保存位圖圖像的屬性。發生此問題時,我讀取值,發生跟隨錯誤:從Android的FirebaseDatabase獲取位圖時出錯Error

com.google.firebase.database.DatabaseException: Class android.graphics.Bitmap is missing a constructor with no arguments 

但我不能覆蓋位圖圖像的構造函數。我怎樣才能解決這種情況?

ref.addListenerForSingleValueEvent(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator(); 
       log("Init ValueEventListener onDataChange()"); 

       while(iterator.hasNext()) { 
        DataSnapshot data = iterator.next(); 
        log("Data : " + data.getKey()); 
        Treino t = data.getValue(Treino.class); 
       } 
      } 
} 

public class Treino implements Serializable{ 

    String nome; 
    List<Exercicio> listaExercicios; 
    List<Integer> listaDiasSemana; 
    String hora; // hh:mm 

    public Treino(String nome, List<Exercicio> listaExercicios, List<Integer> listaDiasSemana, String hora) { 
     this.nome = nome; 
     this.listaExercicios = listaExercicios; 
     this.listaDiasSemana = listaDiasSemana; 
     this.hora = hora; 
    } 

public class Exercicio implements Serializable { 

    String nome, tipo, nomeImagem; 
    Bitmap imagem; 

    public Exercicio() { 
    } 

    public Exercicio(String nome, Bitmap imagem, String nomeImagem) { 
     this.nome = nome; 
     this.imagem = imagem; 
     this.nomeImagem = nomeImagem; 
    } 

我省略了getters和setters。

回答

1

您必須位圖轉換爲字符串

這是代碼

public String BitMapToString(Bitmap bitmap){ 
     ByteArrayOutputStream ByteStream=new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG,100, ByteStream); 
     byte [] b=ByteStream.toByteArray(); 
     String temp=Base64.encodeToString(b, Base64.DEFAULT); 
     return temp; 
    } 

而且Exercicio.class

public class Exercicio implements Serializable { 

String nome, tipo, nomeImagem; 
String bitmapImageString; 

public Exercicio() { 
} 

public Exercicio(String nome, String imagem, String nomeImagem) { 
    this.nome = nome; 
    this.bitmapImageString = imagem; 
    this.nomeImagem = nomeImagem; 
} 
} 

從服務器時,你得到的字符串。您必須將字符串轉換爲位圖

public Bitmap StringToBitMap(String encodedString){ 
try{ 
    byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT); 
    Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); 
    return bitmap; 
}catch(Exception e){ 
    e.getMessage(); 
    return null; 
} 
} 

希望!幫你!

+0

是的,它的作品! – Augusto