-1

I have a problem with NullPointerException when i try to access variables from object i initialized in inner class.But inside the inner class it has all the elements set,and everything is fine.

public class FirebaseConnectionStream extends FirebaseConnection {


   private Object DownloadResult;

   public void publish(String path,Map<String,Object> map){
        try{
       DatabaseReference ref = database.getReference(path);
       ref.updateChildren(map);
     }
    catch(Exception e){
        e.printStackTrace();
    }
 }
 public <T> PortfolioInfo download(String path,final T object){

    try{
        DatabaseReference ref = database.getReference(path);
        ref.addValueEventListener(new ValueEventListener(){

            @Override
            public void onCancelled(DatabaseError arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDataChange(DataSnapshot arg0) { 
                try{
                DownloadResult = arg0.getValue(object.getClass());
                PortfolioInfo p = (PortfolioInfo) DownloadResult;
                System.out.println(p.getId()); // This line here works?
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }   
        });
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return (PortfolioInfo) DownloadResult; // But this one does not?

    }

}

1 Answers1

1

The methods in ValueEventListener are asynchronous, when you try to return DownloadResult, onDataChange will not be called yet and because of that DownloadResult will be null.

merterpam
  • 765
  • 6
  • 14