2016-07-30 47 views
0

我正在開發使用Firebase技術的基本Android聊天應用程序。關於將圖片上傳到Firebase數據庫有一個問題。我點擊ImageButton從我的畫廊中選擇一個圖像。當我選擇圖片時,我的圖片無法上傳到Firebase數據庫。相反,我的應用程序崩潰,將圖片上傳到Firebase時發生NullPointerException

private static final int RC_PHOTO_PICKER = 1;  
ImageButton imageBtn;        
private FirebaseStorage storage;      
private DatabaseReference databaseRef;    
private StorageReference storageRef;     
private FirebaseApp app;        
private FirebaseDatabase database; 

@Override            
protected void onCreate(Bundle savedInstanceState)  
{    


    // image upload code                           

    app = FirebaseApp.getInstance();                       
    database = FirebaseDatabase.getInstance(app);                    
    storage = FirebaseStorage.getInstance(app);                     
    storageRef=storage.getReferenceFromUrl("gs://friendlychat-8a091.appspot.com/");            
    storageRef=storage.getReference("images");                     

    imageBtn = (ImageButton)findViewById(R.id.imageBtn);                  
    imageBtn.setOnClickListener(new View.OnClickListener()                  
    {                               
     public void onClick(View v)                        
     {                              
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);                
      intent.setType("image/jpeg");                      
      intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);                  
      startActivityForResult(Intent.createChooser(intent, getString(R.string.complete_action_with)), RC_PHOTO_PICKER); 
     }                              
    });                               


}        

    @Override                   
    protected void onActivityResult(int requestCode, int resultCode, Intent data)  
    { 
      if(requestCode==RC_PHOTO_PICKER && resultCode==RESULT_OK)                
     {                              
      Uri selectedImageUri = data.getData();                    
      final StorageReference PhotoRef=storageRef.child("images/"+selectedImageUri.getLastPathSegment());     

      PhotoRef.putFile(selectedImageUri)                     
       .addOnFailureListener(new OnFailureListener() {                
        @Override                        
        public void onFailure(@NonNull Exception exception)              
        {                          
        Toast.makeText(getApplicationContext(),"error ="+exception.getMessage(),Toast.LENGTH_LONG).show(); 
        }                          
       })                           
       .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {        
        @Override                        
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {           
         Uri downloaduri = taskSnapshot.getDownloadUrl();              
         mMessageEditText.setText(downloaduri.toString());             

        }                          
       });                           

     }                                                
    } 

這是logcat的消息時,我選擇的圖像形成畫廊

07-30 18:50:00.946 5268-5268/com.google.firebase.codelab.friendlychat D/MainActivity: onActivityResult: requestCode=1, resultCode=-1 
07-30 18:50:00.962 5268-5268/com.google.firebase.codelab.friendlychat D/AndroidRuntime: Shutting down VM 
07-30 18:50:00.962 5268-5268/com.google.firebase.codelab.friendlychat W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x411342a0) 
07-30 18:50:01.188 5268-5268/com.google.firebase.codelab.friendlychat D/FirebaseCrashApiImpl: throwable java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/757 (has extras) }} to activity {com.google.firebase.codelab.friendlychat/com.google.firebase.codelab.friendlychat.MainActivity}: java.lang.NullPointerException 
07-30 18:50:01.290 5268-5268/com.google.firebase.codelab.friendlychat E/AndroidRuntime: FATAL EXCEPTION: main 
                         java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/757 (has extras) }} to activity {com.google.firebase.codelab.friendlychat/com.google.firebase.codelab.friendlychat.MainActivity}: java.lang.NullPointerException 
                          at android.app.ActivityThread.deliverResults(ActivityThread.java:3179) 
                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222) 
                          at android.app.ActivityThread.access$1100(ActivityThread.java:140) 
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276) 
                          at android.os.Handler.dispatchMessage(Handler.java:99) 
                          at android.os.Looper.loop(Looper.java:137) 
                          at android.app.ActivityThread.main(ActivityThread.java:4895) 
                          at java.lang.reflect.Method.invokeNative(Native Method) 
                          at java.lang.reflect.Method.invoke(Method.java:511) 
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994) 
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761) 
                          at dalvik.system.NativeStart.main(Native Method) 
                         Caused by: java.lang.NullPointerException 
                          at com.google.firebase.codelab.friendlychat.MainActivity.onActivityResult(MainActivity.java:329) 
                          at android.app.Activity.dispatchActivityResult(Activity.java:5347) 
                          at android.app.ActivityThread.deliverResults(ActivityThread.java:3175) 
                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222)  
                          at android.app.ActivityThread.access$1100(ActivityThread.java:140)  
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)  
                          at android.os.Handler.dispatchMessage(Handler.java:99)  
                          at android.os.Looper.loop(Looper.java:137)  
                          at android.app.ActivityThread.main(ActivityThread.java:4895)  
                          at java.lang.reflect.Method.invokeNative(Native Method)  
                          at java.lang.reflect.Method.invoke(Method.java:511)  
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)  
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)  
                          at dalvik.system.NativeStart.main(Native Method)  

07-30 18:53:01.196 5268-5270/com.google.firebase.codelab.friendlychat D/dalvikvm: GC_CONCURRENT freed 454K, 10% free 10859K/12039K, paused 19ms+7ms, total 76ms 
07-30 18:53:01.259 5268-5276/com.google.firebase.codelab.friendlychat D/AbsListView: [unregisterDoubleTapMotionListener] 
07-30 18:53:01.259 5268-5276/com.google.firebase.codelab.friendlychat I/MotionRecognitionManager: .unregisterListener :/listener count = 0->0, [email protected] 
+0

如果您的應用程序已經崩潰,然後按[編輯]與logcat的請 –

+0

請端口你的logcat錯誤信息讓我們去調試。對於任何人來說,「不幸的應用程序已停止工作」消息都無法幫助您。 –

+0

您在'MainActivity'的第329行有'NullPointerException'。在那裏設置一個斷點並查看哪個變量爲'null'。請參閱http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it。除此之外:您不會將圖片上傳到Firebase數據庫,而是上傳到Firebase存儲。這是一件好事(Firebase存儲用於存儲這些文件),但它是一個完全不同的API。 –

回答

0
@Override 
public void onClick(View view) 
{ 
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
intent.addCategory(Intent.CATEGORY_OPENABLE); 
intent.setType("image/*"); 
startActivityForResult(intent, REQUEST_IMAGE); 
} 
+1

有關如何解決問題的簡短說明將會很有幫助。 – yakobom

+0

上述代碼導致錯誤,因爲Intent不正確,因爲onActivityResult從此Intent得到了導致NullPointerException(滾動到右邊以在logcat中查看它)的結果。我的代碼有一個Intent,它查找要打開的文檔,它是可打開的類別,其類型是圖像,*表示可以選擇任何圖像格式。 –