HELP! - Camera Preview Crashes


#1

Hello,

This is my first post. I’ve found this forum extremely useful and look forward to helping others as I gain more and more experience.

Okay. I have scoured the forum trying to locate my error. I am hoping someone will be able to assist. I’ve spent about six hours trying to figure out what I’ve done wrong. I get an error stating that CriminalIntent has stopped working upon clicking on the photo button. However, Criminal Intent doesn’t actually stop. The preview is the only thing that stops working. Here is all of my code.

LogCat:

09-14 10:42:59.631: E/AndroidRuntime(2014): FATAL EXCEPTION: main
09-14 10:42:59.631: E/AndroidRuntime(2014): Process: com.bignerdranch.android.criminalintent, PID: 2014
09-14 10:42:59.631: E/AndroidRuntime(2014): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.criminalintent/com.bignerdranch.android.criminalintent.CrimeCameraActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.os.Handler.dispatchMessage(Handler.java:102)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.os.Looper.loop(Looper.java:136)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread.main(ActivityThread.java:5017)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at java.lang.reflect.Method.invokeNative(Native Method)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at java.lang.reflect.Method.invoke(Method.java:515)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at dalvik.system.NativeStart.main(Native Method)
09-14 10:42:59.631: E/AndroidRuntime(2014): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.view.ViewGroup.addView(ViewGroup.java:3415)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.view.ViewGroup.addView(ViewGroup.java:3360)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.view.ViewGroup.addView(ViewGroup.java:3336)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.NoSaveStateFrameLayout.wrap(NoSaveStateFrameLayout.java:40)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.Activity.performStart(Activity.java:5241)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
09-14 10:42:59.631: E/AndroidRuntime(2014): 	... 11 more
09-14 10:43:07.121: I/Process(2014): Sending signal. PID: 2014 SIG: 9
09-14 10:43:09.181: E/CrimeLab(2040): Error loading crimes: 
09-14 10:43:09.181: E/CrimeLab(2040): org.json.JSONException: No value for title
09-14 10:43:09.181: E/CrimeLab(2040): 	at org.json.JSONObject.get(JSONObject.java:355)
09-14 10:43:09.181: E/CrimeLab(2040): 	at org.json.JSONObject.getString(JSONObject.java:515)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.Crime.<init>(Crime.java:29)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.CriminalIntentJSONSerializer.loadCrimes(CriminalIntentJSONSerializer.java:45)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.CrimeLab.<init>(CrimeLab.java:27)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.CrimeLab.get(CrimeLab.java:36)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.CrimeListFragment.onCreate(CrimeListFragment.java:38)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:1879)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:215)
09-14 10:43:09.181: E/CrimeLab(2040): 	at com.bignerdranch.android.criminalintent.SingleFragmentActivity.onCreate(SingleFragmentActivity.java:14)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.Activity.performCreate(Activity.java:5231)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.os.Handler.dispatchMessage(Handler.java:102)
09-14 10:43:09.181: E/CrimeLab(2040): 	at android.os.Looper.loop(Looper.java:136)

CrimeCameraActivity:

public class CrimeCameraActivity extends SingleFragmentActivity {
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		//Hide the window title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		//Hide the status bar and other OS Level chrome
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		super.onCreate(savedInstanceState);
	}

	@Override
	protected Fragment createFragment() {
		return new CrimeCameraFragment();
	}

}

CrimeCameraFragment:

public class CrimeCameraFragment extends Fragment {
	
	private static final String TAG = "CrimeCameraFragment";
	public static final String EXTRA_PHOTO_FILENAME = "com.bignerdranch.android.criminalintent.photo.filename";
	
	private Camera mCamera;
	private SurfaceView mSurfaceView;
	
	private View mProgressContainer;
	
	//simple algorith to acquire screen size from phone - method
	private Size getBestSupportedSize(List<Size> sizes, int width, int height){
		Size bestSize = sizes.get(0);
		int largestArea = bestSize.width * bestSize.height;
		for (Size s : sizes){
			int area = s.width * s.height;
			if (area > largestArea){
				bestSize = s;
				largestArea = area;
			}
		}
		return bestSize;
	}
	
	private Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {
		
		@Override
		public void onShutter() {
			// Display the progress indicator
			mProgressContainer.setVisibility(View.VISIBLE);
		}
	};
	
	private Camera.PictureCallback mJpegCallback = new Camera.PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// Creat File Name
			String filename = UUID.randomUUID().toString() + ".jpg";
			
			//Save the jpeg data to disk
			FileOutputStream os = null;
			boolean success = true;
			
			try{
				os = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
				os.write(data);
			} catch (Exception e){
				Log.e(TAG, "Erro writing to file " + filename, e);
				success = false;
			}finally {
				try{
					if (os != null)
						os.close();
				}catch (Exception e){
					Log.e(TAG, "Error closing file " + filename, e);
					success = false;
				}
			}
			
			if (success){
				Intent i = new Intent();
				i.putExtra(EXTRA_PHOTO_FILENAME, filename);
				getActivity().setResult(Activity.RESULT_OK, i);
			}else{
				getActivity().setResult(Activity.RESULT_CANCELED);
			}
			
			getActivity().finish();
		}
	};
	
	
	@Override
	@SuppressWarnings("deprecation")
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
		View v = inflater.inflate(R.layout.fragment_crime_camera, parent);
		
		mProgressContainer = v.findViewById(R.id.crime_camera_progressContainer);
		mProgressContainer.setVisibility(View.INVISIBLE);
		
		Button takePictureButton = (Button)v
				.findViewById(R.id.crime_camera_takePictureButton);
		takePictureButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (mCamera != null){
					mCamera.takePicture(mShutterCallback, null, mJpegCallback);
				}
				
			}
		});
		
		mSurfaceView = (SurfaceView)v.findViewById(R.id.crime_camera_surfaceview);
		SurfaceHolder holder = mSurfaceView.getHolder();
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		holder.addCallback(new SurfaceHolder.Callback() {
			
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				// We can no longer display on this surface, so stop 
				if(mCamera != null){
					mCamera.stopPreview();
				}
				
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				//Tell the camera to use this surface as it's preview
				try{
					if(mCamera != null){
						mCamera.setPreviewDisplay(holder);
					}
				}catch (IOException exception){
					Log.e(TAG, "Error setting up preview display", exception);
				}
				
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				if(mCamera == null) return;
				
				//The surface has changed size; update the camera preview
				Camera.Parameters parameters = mCamera.getParameters();
				Size s = getBestSupportedSize(parameters.getSupportedPreviewSizes(), width, height);
				parameters.setPreviewSize(s.width, s.height);
				s = getBestSupportedSize(parameters.getSupportedPictureSizes(), width, height);
				parameters.setPictureSize(s.width, s.height);
				mCamera.setParameters(parameters);
				try{
					mCamera.startPreview();
				}catch (Exception e){
					Log.e(TAG,"Could not start preview", e);
					mCamera.release();
					mCamera = null;
				}
			}
		});
		
		
		return v;
		
	}
	
	@TargetApi(9)
	@Override
	public void onResume(){
		super.onResume();
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD){
			mCamera = Camera.open(0);
		}else{
			mCamera = Camera.open();
		}
			
	}
	
	@Override
	public void onPause(){
		super.onPause();
		if (mCamera != null){
			mCamera.release();
			mCamera = null;
		}
	}
	

}

fragment_crime_camera.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        
    <SurfaceView
        android:id="@+id/crime_camera_surfaceview"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        ></SurfaceView>
    
	<Button
	    android:id="@+id/crime_camera_takePictureButton"
	    android:layout_width="wrap_content"
	    android:layout_height="match_parent"
	    android:text="@string/take"
	    />
        
    </LinearLayout>
    
    <FrameLayout 
        android:id="@+id/crime_camera_progressContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true">
        
        <ProgressBar 
            style="@android:style/Widget.ProgressBar.Large"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />
    </FrameLayout>
    
    

</FrameLayout>

CrimeFragment:

public class CrimeFragment extends Fragment {
	
	private ImageButton mPhotoButton;
	
	private static final String TAG = "CrimeFragment";
	
	public static final String EXTRA_CRIME_ID=
			"com.bignerdranch.android.criminalintent.crime_id";
	
	private static final String DIALOG_DATE = "date";
	private static final int REQUEST_DATE = 0;
	private static final int REQUEST_PHOTO = 1;
	
	private Crime mCrime;
	private EditText mTitleField;
	private Button mDateButton;
	private CheckBox mSolvedCheckBox;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
		
		mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
		
		setHasOptionsMenu(true);
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
		case android.R.id.home:
			if(NavUtils.getParentActivityName(getActivity())!= null)
				NavUtils.navigateUpFromSameTask(getActivity());
			//to be implemented next
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onPause(){
		super.onPause();
		CrimeLab.get(getActivity()).saveCrimes();
	}
	
	@TargetApi(11)
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, 
			Bundle savedInstanceState){
		View v = inflater.inflate(R.layout.fragment_crime, parent, false);
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			if (NavUtils.getParentActivityName(getActivity()) != null)
			getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		
		mTitleField = (EditText)v.findViewById(R.id.crime_title);
		mTitleField.setText(mCrime.getTitle());
		mTitleField.addTextChangedListener(new TextWatcher(){
			public void onTextChanged(
					CharSequence c, int start, int before, int count){
				mCrime.setTitle(c.toString());
		}
		

			@Override
			public void beforeTextChanged(CharSequence c, int start,
					int count, int after) {
				// this space intentionally left blank
				
			}


			@Override
			public void afterTextChanged(Editable c) {
				//this space intentionally left blank
				
			}
	});
		
		mDateButton = (Button)v.findViewById(R.id.crime_date);
		updateDate();
		mDateButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View arg0) {
				FragmentManager fm = getActivity()
						.getSupportFragmentManager();
				DatePickerFragment dialog = DatePickerFragment
						.newInstance(mCrime.getDate());
				dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
				dialog.show(fm, DIALOG_DATE);
			}
			
		});
		
		mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
		mSolvedCheckBox.setChecked(mCrime.isSolved());
		mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// set teh crime's solved property
				mCrime.setSolved(isChecked);
			}
			
		});
		
		mPhotoButton = (ImageButton)v.findViewById(R.id.crime_imageButton);
		mPhotoButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getActivity(), CrimeCameraActivity.class);
				startActivityForResult(i, REQUEST_PHOTO);
			}
		});
		
		
        // if camera is not available, disable camera functionality
        PackageManager pm = getActivity().getPackageManager();
        boolean hasACamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) ||
                pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) || 
                Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD ||
                Camera.getNumberOfCameras() > 0;
        if (!hasACamera) {
            mPhotoButton.setEnabled(false);
        }
			return v;
			
	}
	
	public static CrimeFragment newInstance(UUID crimeId){
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_CRIME_ID, crimeId);
		
		CrimeFragment fragment = new CrimeFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if (resultCode != Activity.RESULT_OK) return;
		if (requestCode == REQUEST_DATE){
			Date date = (Date)data
					.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
			mCrime.setDate(date);
			mDateButton.setText(mCrime.getDate().toString());
		}else if (requestCode == REQUEST_PHOTO){
			//Create a new phot object and attach it to the crime
			String filename = data
					.getStringExtra(CrimeCameraFragment.EXTRA_PHOTO_FILENAME);
			if (filename != null){
				Log.i(TAG, "filename: " + filename);
			}
		}
	}
	
	public void updateDate(){
		mDateButton.setText(mCrime.getDate().toString());
	}
}

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bignerdranch.android.criminalintent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="20" />
    
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.hardware.camera"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".CrimeListActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       	</activity>
        <activity 
            android:name=".CrimePagerActivity"
            android:label="@string/app_name">
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".CrimeListActivity"/>
        </activity>
        <activity 
            android:name=".CrimeCameraActivity"
            android:screenOrientation="landscape"
            android:label="@string/app_name">
            
        </activity>
        
        
    </application>

</manifest>

Any and all help is greatly appreciated! I have gone over my code and cannot locate what I’ve done wrong. Thank you!

Sincerely,
Climacus


#2

This post seems dead, no responses, but I got the same problem.
Using Genymotion emulator.
Everything works fine until I’m trying to take a picture.
After crash on trying take picture, I’m returned back to list and if I added title for “crime”, then I see that crime as added in crime list…
What LogCat says:

CrimeFragment.java

[code]public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = “criminalintent.CRIME_ID”;
private static final String DIALOG_DATE = “date”;
private static final int REQUEST_DATE = 0;

Crime mCrime;
EditText mTitleField;
Button mDateButton;
CheckBox mSolvedCheckBox;
ImageButton mPhotoButton;

public static CrimeFragment newInstance(UUID crimeId) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CRIME_ID, crimeId);

    CrimeFragment fragment = new CrimeFragment();
    fragment.setArguments(args);

    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
    mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);

    setHasOptionsMenu(true);
}

public void updateDate() {
    mDateButton.setText(mCrime.getDate().toString());
}

@Override
@TargetApi(11)
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_crime, parent, false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
    }
    
    mTitleField = (EditText)v.findViewById(R.id.crime_title);
    mTitleField.setText(mCrime.getTitle());
    mTitleField.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence c, int start, int before, int count) {
            mCrime.setTitle(c.toString());
        }

        public void beforeTextChanged(CharSequence c, int start, int count, int after) {
            // this space intentionally left blank
        }

        public void afterTextChanged(Editable c) {
            // this one too
        }
    });
    
    mDateButton = (Button)v.findViewById(R.id.crime_date);
    updateDate();
    mDateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            FragmentManager fm = getActivity()
                    .getSupportFragmentManager();
            DatePickerFragment dialog = DatePickerFragment
                .newInstance(mCrime.getDate());
            dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
            dialog.show(fm, DIALOG_DATE);
        }
    });

    mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
    mSolvedCheckBox.setChecked(mCrime.isSolved());
    mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // set the crime's solved property
            mCrime.setSolved(isChecked);
        }
    });
    
    mPhotoButton = (ImageButton)v.findViewById(R.id.crime_imageButton);
    mPhotoButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // launch the camera activity
            Intent i = new Intent(getActivity(), CrimeCameraActivity.class);
            startActivity(i);
        }
    });
    
    // if camera is not available, disable camera functionality
    PackageManager pm = getActivity().getPackageManager();
    boolean hasACamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) ||
            pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) ||
            Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD ||
            Camera.getNumberOfCameras() > 0;
    if (!hasACamera) {
        mPhotoButton.setEnabled(false);
    }

    return v; 
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_DATE) {
        Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
        mCrime.setDate(date);
        updateDate();
    }
}

@Override
public void onPause() {
    super.onPause();
    CrimeLab.get(getActivity()).saveCrimes();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(getActivity());
            return true;
        default:
            return super.onOptionsItemSelected(item);
    } 
}

}[/code]
CrimeCameraActivity.java

[code]public class CrimeCameraActivity extends SingleFragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
	super.onCreate(savedInstanceState);
}

@Override
protected Fragment createFragment() {
	return new CrimeCameraFragment();
}

}
[/code]
CrimeCameraFragment.java

[code]public class CrimeCameraFragment extends Fragment {
private static final String TAG = “CrimeCameraFragment”;

private Camera mCamera;
private SurfaceView mSurfaceView;

@Override
@SuppressWarnings("deprecation")
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
		Bundle savedInstanceState) {
	View v = inflater.inflate(R.layout.fragment_crime_camera, parent);
	
	Button takePictureButton = (Button)v
			.findViewById(R.id.crime_camera_takePictureButton);
	takePictureButton.setOnClickListener(new View.OnClickListener() {
		
		public void onClick(View v) {
			getActivity().finish();
		}
	});
	mSurfaceView = (SurfaceView)v.findViewById(R.id.crime_camera_surfaceView);
	SurfaceHolder holder = mSurfaceView.getHolder();
	holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	
	holder.addCallback(new SurfaceHolder.Callback() {
		
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub				
		}

		public void surfaceChanged(SurfaceHolder holder, int format,
			int width, int height) {
			if (mCamera == null) return;
			Camera.Parameters parameters = mCamera.getParameters();
			Size s = getBestSupportedSize(parameters.getSupportedPreviewSizes(), width, height);
			parameters.setPreviewSize(s.width, s.height);
			mCamera.setParameters(parameters);
				try {
					mCamera.startPreview();
				} catch (Exception e) {
					Log.e(TAG, "Could not start preview", e);
					mCamera.release();
					mCamera = null;
				}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub				
		}
		
	});
	
	return v;
}

@TargetApi(9)
@Override
public void onResume() {
	super.onResume();
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
		mCamera = Camera.open(0);
	} else {
		mCamera = Camera.open();
	}
}

@Override
public void onPause() {
	super.onPause();
	if (mCamera != null) {
		mCamera.release();
		mCamera = null;
	}
}

private Size getBestSupportedSize(List<Size> sizes, int width, int height) {
	Size bestSize = sizes.get(0);
	int largestArea = bestSize.width * bestSize.height;
	for (Size s : sizes) {
		int area = s.width * s.height;
		if(area > largestArea) {
			bestSize = s;
			largestArea = area;
		}
	}
	return bestSize;
}

}[/code]


#3

In method onCreateView of class CrimeCameraFragment.java, calling inflater.inflate(…) with “false” as the value of third parameter.
This means you need to change:
View v = inflater.inflate(R.layout.fragment_crime_camera, parent);
to:
View v = inflater.inflate(R.layout.fragment_crime_camera, parent, false);


#4

[quote=“wangchunyang”]In method onCreateView of class CrimeCameraFragment.java, calling inflater.inflate(…) with “false” as the value of third parameter.
This means you need to change:
View v = inflater.inflate(R.layout.fragment_crime_camera, parent);
to:
View v = inflater.inflate(R.layout.fragment_crime_camera, parent, false);[/quote]

Yes, this helped. Thank You!
Should read more docs on dev android page…