2016-11-17 130 views
-2

我正在製作一個應用程序,其中的一項功能是用戶可以將圖像和視頻上傳到服務器 它在活動中運行良好,但現在我想在片段中使用它。我嘗試有效地編寫代碼,並且在編譯過程中我沒有收到任何錯誤,而且我的應用程序運行成功,但是當我點擊片段時,它顯示「不幸的應用程序已停止」,並且在日誌中出現此錯誤:嘗試調用虛擬方法'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)'null對象引用

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

及其分這條線:

public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
    this line ➦ fileUri = savedInstanceState.getParcelable("file_uri"); 
    } 

我不知道什麼是錯

我的代碼:

public class TabFragment4 extends Fragment implements View.OnClickListener{ 

View parentHolder; 
private static final String TAG = MainActivity.class.getSimpleName(); 


int req_code = 100; 
int video_code = 20; 
String path; 
Uri selectedImageUri; 
// Camera activity request codes 
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10; 
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200; 

public static final int MEDIA_TYPE_IMAGE = 1; 
public static final int MEDIA_TYPE_VIDEO = 2; 
Context mContext; 
private Uri fileUri; // file url to store image/video 

private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location; 


public TabFragment4() { 
    // Required empty public constructor 
} 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
} 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false); 

    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 


     AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity()); 

     // Setting Dialog Title 
     mAlertDialog.setTitle("Location not available, Open GPS?") 
       .setMessage("Activate GPS to use Location Service ?") 
       .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(intent); 
        } 
       }) 
       .setNegativeButton("Cancel",new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         dialog.cancel(); 
        } 
       }).show(); 


     // Call your Alert message 
    } 

    btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture); 
    btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo); 
    gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery); 

    videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery); 
    location=(ImageButton)parentHolder.findViewById(R.id.location); 

    videobtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      video(); 
     } 
    }); 
    gallerybtn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // record video 
      galleryimage(); 
     } 
    }); 
    btnCapturePicture.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // record video 
      captureImage(); 
     } 
    }); 

    /** 
    * Capture image button click event 
    */ 

    btnRecordVideo.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // record video 
      recordVideo(); 
     } 
    }); 
    /** 
    * Record video button click event 
    */ 
    btnRecordVideo.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // record video 
      recordVideo(); 
     } 
    }); 

    return parentHolder; 
    } 



public void video(){ 
    Intent intent = new Intent(); 
    intent.setType("video/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, 
      "Select file to upload "), video_code); 
} 

public void galleryimage(){ 
    Intent intent = new Intent(); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, 
      "Select file to upload "), req_code); 
} 

public String getPath(Uri uri) { 

    String[] projection = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
    cursor.moveToFirst(); 

    return cursor.getString(column_index); 
} 

private void captureImage() { 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); 

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 

    // start the image capture Intent 
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); 
} 

/** 
* Launching camera app to record video 
*/ 
private void recordVideo() { 
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); 

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); 

    // set video quality 
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file 
    // name 

    // start the video capture Intent 
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE); 
} 

public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

    // save file url in bundle as it will be null on screen orientation 
    // changes 
    outState.putParcelable("file_uri", fileUri); 
} 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 

    super.onActivityCreated(savedInstanceState); 

    fileUri = savedInstanceState.getParcelable("file_uri"); 


} 




public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // if the result is capturing Image 

    if (requestCode == req_code) { 
     selectedImageUri = data.getData(); 

     if (resultCode ==Activity. RESULT_OK) { 
      path = getPath(selectedImageUri); 
      launchUpload(true); 

      System.out.println("selectedPath1 : " + path); 
     } 
    } 

    if (requestCode == video_code) { 
     selectedImageUri = data.getData(); 

     if (resultCode == Activity. RESULT_OK) { 
      path = getPath(selectedImageUri); 
      launchUpload(false); 

      System.out.println("selectedPath1 : " + path); 
     } 
    } 


    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { 
     if (resultCode == Activity.RESULT_OK) { 

      //successfully captured the image 
      // launching upload activity 
      launchUploadActivity(true); 

      //Intent intent = new Intent(this,UploadActivity.class); 
      //startActivity(intent); 

     } else if (resultCode ==Activity. RESULT_CANCELED) { 

      // user cancelled Image capture 
      Toast.makeText(getActivity(), 
        "User cancelled image capture", Toast.LENGTH_SHORT) 
        .show(); 

     } else { 
      // failed to capture image 
      Toast.makeText(getActivity(), 
        "Sorry! Failed to capture image", Toast.LENGTH_SHORT) 
        .show(); 
     } 

    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) { 
     if (resultCode == Activity.RESULT_OK) { 

      // video successfully recorded 
      // launching upload activity 
      launchUploadActivity(false); 



     } else if (resultCode == Activity.RESULT_CANCELED) { 

      // user cancelled recording 
      Toast.makeText(getActivity(), 
        "User cancelled video recording", Toast.LENGTH_SHORT) 
        .show(); 

     } else { 
      // failed to record video 
      Toast.makeText(getActivity(), 
        "Sorry! Failed to record video", Toast.LENGTH_SHORT) 
        .show(); 
     } 
    } 
} 


private void launchUploadActivity(boolean isImage) { 
    Intent i = new Intent(getActivity(), UploadActivity.class); 
    i.putExtra("filePath", fileUri.getPath()); 
    i.putExtra("isImage", isImage); 

    startActivity(i); 
} 
private void launchUpload(boolean isImage) { 
    Intent i = new Intent(getActivity(), UploadActivity.class); 
    i.putExtra("filePath", path); 
    i.putExtra("isImage", isImage); 

    startActivity(i); 
} 

/** 
* ------------ Helper Methods ---------------------- 
* */ 

/** 
* Creating file uri to store image/video 
*/ 
public Uri getOutputMediaFileUri(int type) { 
    return Uri.fromFile(getOutputMediaFile(type)); 
} 

/** 
* returning image/video 
*/ 
private static File getOutputMediaFile(int type) { 

    // External sdcard location 
    File mediaStorageDir = new File(
      Environment 
        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
      Config.IMAGE_DIRECTORY_NAME); 

    // Create the storage directory if it does not exist 
    if (!mediaStorageDir.exists()) { 
     if (!mediaStorageDir.mkdirs()) { 
      Log.d(TAG, "Oops! Failed create " 
        + Config.IMAGE_DIRECTORY_NAME + " directory"); 
      return null; 
     } 
    } 

    // Create a media file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", 
      Locale.getDefault()).format(new Date()); 
    File mediaFile; 
    if (type == MEDIA_TYPE_IMAGE) { 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator 
       + "IMG_" + timeStamp + ".jpg"); 
    } else if (type == MEDIA_TYPE_VIDEO) { 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator 
       + "VID_" + timeStamp + ".mp4"); 
    } else { 
     return null; 
    } 

    return mediaFile; 
} 





@Override 
public void onClick(View v) { 




} 
} 

回答

0

似乎savedInstanceState == null所以使用類似這樣的東西:

if (savedInstanceState != null) { 
    fileUri = savedInstanceState.getParcelable("file_uri"); 
} else { 
    fileUri = ??? - what You want do to in else case; 
} 
+0

感謝它的工作...... –

相關問題