2013-11-15 310 views
0

在我的應用程序中,我在我的佈局上顯示圖像(picattach.png)。照片附加後,圖片應該換成另一張(picattached.png)。我的問題是,應用程序崩潰了:setImageResource造成崩潰

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,   request=65541, result=-1, data=Intent { dat=content://media/external/images/media/9688  flg=0x1 }} to activity {com.peekatucorp.peekatu/com.peekatucorp.peekatu.MainActivity}: java.lang.NullPointerException 

當我嘗試和setImageResource中選擇圖像的onActivityResult表明圖像已被選中。

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    Log.v("response", "Photo Selected"); 

    if(requestCode == 5 && data != null && data.getData() != null){ 
      b2.setImageResource(R.drawable.picattached); 
      Uri _uri = data.getData(); 
      Log.v("response", "cp1/4"); 
      if (_uri != null) { 
       //User has pick an image. 
       Cursor cursor = getActivity().getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null); 
       cursor.moveToFirst(); 
       Log.v("response", "cp2/4"); 
       //Link to the image 
       final String imageFilePath = cursor.getString(0); 
       Log.v("response", "cp3/4"); 
       uploadMsgPic = imageFilePath; 
       Log.v("response", "4/4"); 
       cursor.close(); 
       media_attached=true; 

      } 

     } 
     super.onActivityResult(requestCode, resultCode, data); 

} 

如果我刪除:

b2.setImageResource(R.drawable.picattached); 

應用程序運行正常。

幫助。

的XML

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
> 

<ListView 
    android:id="@+id/listView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/form" 
    android:layout_alignParentTop="true" 
    android:choiceMode="none" 
    android:divider="#00000000" 
    android:dividerHeight="@dimen/zerosize" 
    android:footerDividersEnabled="false" 
    android:headerDividersEnabled="false" 
    android:listSelector="@android:color/transparent"> 

</ListView> 

<RelativeLayout 
    android:id="@+id/form" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:orientation="vertical" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="40dp" 
     android:background="@drawable/inputbg" > 

     <EditText 
      android:id="@+id/cr_room_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_toLeftOf="@+id/sendMessage" 
      android:layout_weight="3" 
      android:ems="10" 
      android:hint="Enter Message" 
      android:inputType="text" /> 

     <ImageView 
      android:id="@+id/postpic" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:src="@drawable/picattach" /> 

     <Button 
      android:id="@+id/sendMessage" 
      style="@style/SingleGradient" 
      android:layout_width="35dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" /> 

    </LinearLayout> 

ImageView的

ImageView b2 = (ImageView) v.findViewById(R.id.postpic); 




b2.setOnClickListener(new View.OnClickListener() { 


    @Override 
    public void onClick(View v) { 
     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, "Select Picture"), 5); 
    } 
}); 

完整堆棧跟蹤

11-15 13:45:17.256: E/AndroidRuntime(17431): FATAL EXCEPTION: main 
11-15 13:45:17.256: E/AndroidRuntime(17431): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65541, result=-1, data=Intent { dat=content://media/external/images/media/8897 flg=0x1 }} to activity {com.peekatucorp.peekatu/com.peekatucorp.peekatu.MainActivity}: java.lang.NullPointerException 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread.deliverResults(ActivityThread.java:3367) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread.access$1100(ActivityThread.java:141) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.os.Handler.dispatchMessage(Handler.java:99) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.os.Looper.loop(Looper.java:137) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread.main(ActivityThread.java:5103) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at java.lang.reflect.Method.invokeNative(Native Method) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at java.lang.reflect.Method.invoke(Method.java:525) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at dalvik.system.NativeStart.main(Native Method) 
11-15 13:45:17.256: E/AndroidRuntime(17431): Caused by: java.lang.NullPointerException 
11-15 13:45:17.256: E/AndroidRuntime(17431): at com.peekatucorp.peekatu.ChatRoomFragment.onActivityResult(ChatRoomFragment.java:92) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:161) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at com.peekatucorp.peekatu.MainActivity.onActivityResult(MainActivity.java:98) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.Activity.dispatchActivityResult(Activity.java:5322) 
11-15 13:45:17.256: E/AndroidRuntime(17431): at android.app.ActivityThread.deliverResults(ActivityThread.java:3363) 
11-15 13:45:17.256: E/AndroidRuntime(17431): ... 11 more 
11-15 13:45:35.896: E/SQLiteLog(17431): (3850) statement aborts at 34: [UPDATE cookies SET last_access_utc=? WHERE creation_utc=?] disk I/O error 
11-15 13:45:35.916: E/SQLiteLog(17431): (1) statement aborts at 2: [COMMIT] cannot commit - no transaction is active 

完全chatfragment.java從開始到按鈕偵聽

package com.peekatucorp.peekatu; 

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Random; 
import java.util.Timer; 
import java.util.TimerTask; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.CompressFormat; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnKeyListener; 
import android.view.ViewGroup; 
import android.view.inputmethod.InputMethodManager; 
import android.view.WindowManager; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.Toast; 

import com.actionbarsherlock.app.SherlockFragment; 
import com.loopj.android.http.AsyncHttpClient; 
import com.loopj.android.http.AsyncHttpResponseHandler; 
import com.loopj.android.http.RequestParams; 

/** 
* Shows just a simple text 
* 
* @author sbaltes 
*/ 
public class ChatRoomFragment extends SherlockFragment { 

    private String title; 
    private com.peekatucorp.peekatu.DiscussArrayAdapter adapter; 
    private ListView lv; 
// private LoremIpsum ipsum; 
    private EditText editText1; 
    private static Random random; 
    private String selected_room; 
    private String last_message; 
    private Document responseDoc; 
    private String type; 
    private String user; 
    private String responseString; 
    private Timer timer; 
    private String last_inbox_message; 
    private ImageView b2; 
    String picurl=null; 
    String uploadMsgPic; 
    Boolean m_iAmVisible=false; 
    Boolean local=false; 
    Boolean media_attached=false; 
    //private SherlockFragmentActivity sfa; 
    public AbstractTabStackNavigationActivity navact; 
    public LayoutInflater inflaterr; 



    @Override 
    public void onPause(){ 
     super.onPause(); 
     Log.v("response", "Being Paused "); 
    } 
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     Log.v("response", "Photo Selected"); 

     if(requestCode == 5 && data != null && data.getData() != null){ 
        Uri _uri = data.getData(); 
       Log.v("response", "cp1/4"); 
       //b2.setImageResource(R.drawable.picattached); 
       if (_uri != null) { 
        //User has pick an image. 
        Cursor cursor = getActivity().getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null); 
        cursor.moveToFirst(); 
        Log.v("response", "cp2/4"); 
        //Link to the image 
        final String imageFilePath = cursor.getString(0); 
        Log.v("response", "cp3/4"); 
        uploadMsgPic = imageFilePath; 
        Log.v("response", "4/4"); 
        cursor.close(); 
        media_attached=true; 

       } 

      } 
      super.onActivityResult(requestCode, resultCode, data); 

    } 


    @Override 
    public void onResume() { 
     super.onResume(); // setText() here 
     Log.v("response", "resumed"); 
     /*if(!uploadMsgPic.equalsIgnoreCase("")){ 
      b2.setImageDrawable(getResources().getDrawable(R.drawable.picattached)); 
      } */ 
     m_iAmVisible = true; 
     if(type.equalsIgnoreCase("1")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("main"); 
     }else if(type.equalsIgnoreCase("2")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu(""); 
     }else if(type.equalsIgnoreCase("3")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("delete_conv",user); 
     }else if(type.equalsIgnoreCase("4")){ 
      MainActivity m = (MainActivity)getActivity(); 
      if(local) 
       m.changeMenu("online_map_local"); 
      else 
       m.changeMenu("online_map_all"); 
      //m.changeMenu("online_map_local"); 
     }else if(type.equalsIgnoreCase("5")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("main"); 
     } 
    // sfa = this.getSherlockActivity(); 
     //this.getSupportActionBar().setTitle("asd"); 
    // Intent i = this.getIntent(); 
     //String type = "1";//i.getExtras().getString("type"); 
     Log.v("response ", "messages type "+type); 
     refreshChat(); 
    } 




    private Bitmap decodeFile(File f, int SIZE) throws IOException{ 
     Bitmap b = null; 

      //Decode image size 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 

     FileInputStream fis = new FileInputStream(f); 
     BitmapFactory.decodeStream(fis, null, o); 
     fis.close(); 

     int scale = 1; 
     if (o.outHeight > SIZE || o.outWidth > SIZE) { 
      scale = (int)Math.pow(2, (int) Math.round(Math.log(SIZE/
       (double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5))); 
     } 

     //Decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize = scale; 
     fis = new FileInputStream(f); 
     b = BitmapFactory.decodeStream(fis, null, o2); 
     fis.close(); 

     return b; 
    } 
    public void refreshChat(){ 
     if(!m_iAmVisible) 
      return; 
     if(type.equalsIgnoreCase("1")){ 
      SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE); 

       String selected_public = preferences.getString("selected_room", "Adult Lobby"); 
      this.getSherlockActivity().getSupportActionBar().setTitle("[email protected]"); 
      this.getSherlockActivity().getSupportActionBar().setSubtitle(selected_public); 


     getChatMessages(); 
     }else if(type.equalsIgnoreCase("2")){ 
      this.getSherlockActivity().getSupportActionBar().setTitle("[email protected]"); 
      this.getSherlockActivity().getSupportActionBar().setSubtitle("Private Messages"); 



      getInboxMessages(); 
     }else if(type.equalsIgnoreCase("3")){ 
      this.getSherlockActivity().getSupportActionBar().setTitle("Conversation"); 
      this.getSherlockActivity().getSupportActionBar().setSubtitle("Username"); 


      getUserMessages("1"); 
     }else if(type.equalsIgnoreCase("4")){ 
      this.getSherlockActivity().getSupportActionBar().setTitle("Online"); 

      //this.getSherlockActivity().getSupportActionBar().setSubtitle("Username"); 

      getUsers(); 
     }else if(type.equalsIgnoreCase("5")){ 
      SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE); 

       String selected_public = preferences.getString("selected_room", "Adult Lobby"); 

      this.getSherlockActivity().getSupportActionBar().setTitle("Users in Room"); 
      this.getSherlockActivity().getSupportActionBar().setSubtitle(selected_public); 
      //this.getSherlockActivity().getSupportActionBar().setSubtitle("Username"); 

      getUsersRoom(); 
     } 

    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) { 
      super.onSaveInstanceState(outState); 
      Log.v("response", "In frag's on save instance state "); 
      outState.putString("response",responseString); 
      // outState.putS(outState); 

      //outState.putSerializable("starttime", lv); 

     } 


    public void waitncall(Boolean failed){ 
     if(getActivity()==null) 
      return; 


     final SharedPreferences preferences = getActivity().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); 
      if(preferences==null) 
       return; 
      int refresh = Integer.parseInt(preferences.getString("loggedin_refresh", "3")); 
      if(failed){ 
       Toast.makeText(this.getActivity(), "Connection Error, retrying in 10 seconds.", 1).show(); 
       refresh=10; 
      } 
      timer = new Timer(); 
      timer.schedule(new TimerTask() { 
       @Override 
       public void run() { 
        if(getActivity()!=null) 
        getActivity().runOnUiThread(new Runnable() { 
         public void run() { 
          Log.v("response", "timer");   
        //stuff that updates ui 
          timer.cancel(); 
           refreshChat(); 

         } 
        }); 
       } 
      }, refresh*1000);//put here time 1000 milliseconds=1 second 

    } 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setRetainInstance(true); 
    } 
    @Override 
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { 
     super.onCreateView(inflater, container, savedInstanceState); 

     uploadMsgPic = ""; 
     m_iAmVisible = true; 
     final View v = inflater.inflate(R.layout.activity_discuss, container, false); 
    // setRetainInstance(true); 
     //last_message = "0"; 
     inflaterr = inflater; 
     last_inbox_message = "99999999999"; 
    /* if(type.equalsIgnoreCase("1")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("main"); 
     }else if(type.equalsIgnoreCase("2")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu(""); 
     }else if(type.equalsIgnoreCase("3")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("delete_conv",user); 
     }else if(type.equalsIgnoreCase("4")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu("online_map"); 
     }else if(type.equalsIgnoreCase("5")){ 
      MainActivity m = (MainActivity)getActivity(); 
      m.changeMenu(""); 
     }*/ 
     final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); 

     if(responseString.length()>0 && preferences.getString("roomchanged", "notchanged").equalsIgnoreCase("notchanged")){ 
      Log.v("response", "Resumed"); 

     }else{ 

      adapter = new DiscussArrayAdapter(inflater.getContext(), R.layout.listitem_discuss,Integer.parseInt(type),getTabStack()); 
      last_message = "1"; 
     } 
     SharedPreferences.Editor editor = preferences.edit(); 
     //editor.putString("selected_room","); 
     editor.putString("roomchanged", "notchanged"); 

     //responseString = ""; 
         if(savedInstanceState!=null && false){ 

          responseString = savedInstanceState.getString("response"); 
         // return super.onCreateView(inflater, container, savedInstanceState); 

         } 



    // ((TextView) tv).setText(title); 
    Log.v("response ", "onCreate "); 

    Log.v("response ", "messages type "); 
    //--SAVE Data 
// preferences = this.getSharedPreferences("MyPreferences", MODE_PRIVATE); 


    //--READ data  
    selected_room = preferences.getString("selected_room", "Lobby"); 
    Log.v("response ", "messages type "); 
    //last_message = "1"; 
    Intent i = this.getActivity().getIntent(); 
    Log.v("response ", "messages type "); 
    //String type = "1";//i.getExtras().getString("type"); 
    Log.v("response ", "messages type "); 
    Log.v("response ", "messages type "+type); 


//setContentView(R.layout.activity_discuss); 

    if(type.equalsIgnoreCase("2") || type.equalsIgnoreCase("4") || type.equalsIgnoreCase("5")){ 

     v.findViewById(R.id.form).setVisibility(View.GONE); 
     //r; 
    } 
    random = new Random(); 
// ipsum = new LoremIpsum(); 
    getActivity().getWindow().setSoftInputMode(
       WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
    lv = (ListView) v.findViewById(R.id.listView1); 

    if(lv==null) 
     Log.v("response ", "lv null"); 
    //adapter = new DiscussArrayAdapter(inflater.getContext(), R.layout.listitem_discuss,Integer.parseInt(type),getTabStack()); 
    if(adapter==null) 
     Log.v("response ", "adapter null"); 
    lv.setAdapter(adapter); 
    Log.v("response ", "messages type "); 
    if(type.equalsIgnoreCase("2")){ 
     lv.setDivider(this.getResources().getDrawable(R.color.gray)); 
     lv.setDividerHeight(1); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
        long id) { 
       OneComment clicked = adapter.getItem(position); 

      /* Fragment newFragment = CountingFragment.newInstance(mStackLevel); 

        // Add the fragment to the activity, pushing this transaction 
        // on to the back stack. 
        FragmentTransaction ft = sfa.getSupportFragmentManager().beginTransaction(); 
        ft.replace(R.id.simple_fragment, newFragment); 
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
        ft.addToBackStack(null); 
        ft.commit();*/ 
       MainActivity m = (MainActivity)getActivity(); 
       final TabInfo tab = m.getCurrentTabInfo(); 
        final ChatRoomFragment fragment = new ChatRoomFragment().setType("3").setNAV(m).setUser(clicked.userid); 
        // fragment.setText(characters[position]); 

        // second, you push the fragment. It becomes visible and the up button is 
        // shown 
        m.pushFragment(tab, fragment); 

      } 
     }); 

     }else if(type.equalsIgnoreCase("4") ||type.equalsIgnoreCase("5")){ 
      lv.setDivider(this.getResources().getDrawable(R.color.gray)); 
      lv.setDividerHeight(1); 
      lv.setOnItemClickListener(new OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        OneComment clicked = adapter.getItem(position); 

       /* Fragment newFragment = CountingFragment.newInstance(mStackLevel); 

         // Add the fragment to the activity, pushing this transaction 
         // on to the back stack. 
         FragmentTransaction ft = sfa.getSupportFragmentManager().beginTransaction(); 
         ft.replace(R.id.simple_fragment, newFragment); 
         ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
         ft.addToBackStack(null); 
         ft.commit();*/ 
        MainActivity m = (MainActivity)getActivity(); 
        final TabInfo tab = m.getCurrentTabInfo(); 
         final ProfileFragment fragment = new ProfileFragment().setUser(clicked.userid); 
         // fragment.setText(characters[position]); 

         // second, you push the fragment. It becomes visible and the up button is 
         // shown 
         m.pushFragment(tab, fragment);      

      } 
      }); 

      } 

     else{ 
     lv.setDivider(this.getResources().getDrawable(R.color.transparent)); 
     lv.setDividerHeight(0); 


    } 
    Button b1 = (Button) v.findViewById(R.id.sendMessage); 

    b1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      if(!uploadMsgPic.equalsIgnoreCase("")){ 

       Log.v("response","Pic in storage"); 
       //PhotoUploadTask uploadpicmsg = new PhotoUploadTask(); 
       //uploadpicmsg.execute(); 
       sendPicMsg(); 
       }else{ 
         sendMessage(); 
        } 
      // it was the 1st button 
      //sendMessage(); 
      //Log.v("response","message sent"); 


      //adapter.add(new OneComment(true, editText1.getText().toString())); 
      //editText1.setText(""); 
      //lv.setSelection(adapter.getCount() - 1); 
      } 
     }); 


    /*if(!uploadMsgPic.equalsIgnoreCase("")){ 
     b2.setImageResource(R.drawable.picattached); 
    }else{ 
     b2.setImageResource(R.drawable.picattach); 
    } */ 

    b2 = (ImageView) v.findViewById(R.id.postpic); 
    b2.setOnClickListener(new View.OnClickListener() { 


     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(); 
      intent.setType("image/*"); 
      intent.setAction(Intent.ACTION_GET_CONTENT); 
      startActivityForResult(Intent.createChooser(intent, "Select Picture"), 5); 
+0

可以請你提供從LogCat整個StackTrace –

+0

已更新問題 – TWeeKeD

+0

它是一個'NullPointerException'。你可以在調用該行時確認'b2'不爲空嗎? – Grambot

回答

0

試試這個:

b2.setImageDrawable(getResources().getDrawable(R.drawable.picattached)); 
0

框架希望你調用它的super.onActivityResult(requestCode, resultCode, data);擺在首位,並應用您的請求處理後if(requestCode == 5 && data != null && data.getData() != null){。不這樣做會導致你的NullPointerException。您應該如下處理onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    Log.v("response", "Photo Selected"); 

    if(requestCode == 5 && data != null && data.getData() != null){ 

P.S.這裏有一個cool article for ya