0

Я пытаюсь сделать boundService в своем приложении, но я не могу получить никакого результата, независимо от того, что он просто возвращает null. Я могу видеть в отладке, что код работает отлично в моей службе, но я подозреваю, что моя деятельность слишком быстрая, поэтому, когда она вызвала службу, theres ничего не даст. Как это исправить?BindService бросает nullpointer, даже если указывать на чистую строку

Это моя деятельность;

import com.example....DownloadPicService.MyBinder; 

import java.io.IOException; 


public class RecievedSB extends AppCompatActivity { 
    public DownloadPicService Dlpic; 
    private LoginActivity.UserLoginTask mAuthTask = null; 
    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener mAuthListener; 
    private static final String TAG = "Login"; 
    private DatabaseReference mPostReference; 
    private TextView recievedCardTextView; 
    private String path1; 

    /** Messenger for communicating with the service. */ 
    DownloadPicService mService; 

    /** Flag indicating whether we have called bind on the service. */ 
    boolean mBound; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_recieved_sb); 
     mPostReference = FirebaseDatabase.getInstance().getReference() 
       .child("users").child(".."); 
     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in 
        Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); 
       } else { 
        // User is signed out 
        Log.d(TAG, "onAuthStateChanged:signed_out"); 
       } 
       // ... 
      } 
     }; 
     recievedCardTextView = (TextView) findViewById(R.id.recievedCardTextView); 


    } 
    @Override 
    public void onStart(){ 
     super.onStart(); 

     if (mAuthTask != null) { 
      return; 
     } 
     ValueEventListener postListener = new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       // Get Post object and use the values to update the UI 
       CardService cid = dataSnapshot.getValue(CardService.class); 
       recievedCardTextView.setText(cid.email); 
       System.out.println(cid.email); 
       // if (mBound) { 

       // } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 
       // Getting Post failed, log a message 
       Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); 
       // ... 
      } 
     }; 
     mPostReference.addValueEventListener(postListener); 

     Intent intent = new Intent(this, DownloadPicService.class); 
     // intent.putExtra("FBservice", "DL"); 
     this.startService(intent); 
     this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
    } 
    @Override 
    protected void onStop() { 
     super.onStop(); 
     unbindService(mConnection); 
    } 
    private ServiceConnection mConnection = new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName className, IBinder service) { 
      // This is called when the connection with the service has been 
      // established, giving us the object we can use to 
      // interact with the service. We are communicating with the 
      // service using a Messenger, so here we get a client-side 
      // representation of that from the raw IBinder object. 
      mBound = true; 
      MyBinder myBinder = (MyBinder) service; 
      mService = myBinder.getService(); 


      try { 
       path1 = Dlpic.getImagePath2(); 
       Log.d(TAG, path1); 
      } 
      catch(IOException e) 
      { 
       System.out.println(e.getMessage()); 
      } 

     } 

     @Override 
     public void onServiceDisconnected(ComponentName className) { 
      // This is called when the connection with the service has been 
      // unexpectedly disconnected -- that is, its process crashed. 
      mService = null; 
      mBound = false; 
     } 
    }; 

} 

Моя служба:

public class DownloadPicService extends Service { 
    FirebaseStorage storage = FirebaseStorage.getInstance(); 
    StorageReference storageRef = storage.getReferenceFromUrl("gs:/..."); 

    private static final String TAG = "DLService"; 
    private FirebaseAuth.AuthStateListener mAuthListener; 
    private String path1; 
    private IBinder mBinder = new MyBinder(); 
    private String path2; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
    } 
    @Override 
    public IBinder onBind(Intent intent) { 
     Log.v(TAG, "in onBind"); 
     return mBinder; 
    } 

    public DownloadPicService() { 
     try { 
      getImagePath2(); 
      Log.d(TAG, "Starter DL"); 

     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 

    public String getImagePath2() throws IOException { 
     StorageReference islandRef = storageRef.child("/userimages/[email protected]/[email protected]"); 

     File localFile = File.createTempFile("images", "jpg"); 
     path1 = localFile.getAbsolutePath(); 

     Log.d(TAG, path1); 
     islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { 
       Log.d(TAG, "worked buddy"); 
       //path2 = path1; 
       /*Intent pic = new Intent(DownloadPicService.this, RecievedSB.class); 
       pic.putExtra("picpath", path1); 
       LocalBroadcastManager.getInstance(DownloadPicService.this).sendBroadcast(pic);*/ 
       } 
     }).addOnFailureListener(new OnFailureListener() { 
      @Override 
      public void onFailure(@NonNull Exception exception) { 
       // Handle any errors 
      } 
     }); 
     return path1; 
    } 
    public String getPath(){ 

     return "hej"; 
    } 

    @Override 
    public boolean onUnbind(Intent intent) { 
     Log.d(TAG, "in onUnbind"); 
     return true; 
    } 

    public class MyBinder extends Binder { 
     public DownloadPicService getService() { 
      return DownloadPicService.this; 
     } 
    } 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.v(TAG, "in onDestroy"); 
    } 

    @Override 
    public void onRebind(Intent intent) { 
     Log.v(TAG, "in onRebind"); 
     super.onRebind(intent); 
    } 
} 
+0

Опубликовать свой логарифм – Raghavendra

+1

Ты совершенно прав, я должен позвонить в mService. Теперь все работает. Спасибо!!! :) – NicklasN

ответ

1

Вы не инициализирован Dlpic обновить свой код,

Dlpic.getImagePath2(); to 

mService.getImagePath2(); 

и попробовать.