我在button
中有一个fragment
。当fragment
被调用并点击button
时,我希望camera
打开。我已经完成了很多教程。但我无法找到在camera
中实施fragment
的解决方案。
这是我的java代码camera.java:
public class camera extends Fragment {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
Button btnCapture;
ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.camera,
container, false);
btnCapture=(Button) rootView.findViewById(R.id.btnCapturePicture);
//imageView = (ImageView) rootView.findViewById(R.id.imageview);
btnCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
}
}
}
}
这是我的camera.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
tools:context="com.example.prakash.eduqueri.fragments.camera">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical">
<!-- Capture picture button
-->
<Button
android:id="@+id/btnCapturePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take a Picture"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp" />
这是我的logcat:
FATAL EXCEPTION: main
Process: com.example.prakash.eduqueri, PID: 14511
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65636, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.prakash.eduqueri/com.example.prakash.eduqueri.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5052)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.prakash.eduqueri.camera.onActivityResult(camera.java:87)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:176)
at android.app.Activity.dispatchActivityResult(Activity.java:5437)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5052)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
new logcat:
Unable to decode stream: java.io.FileNotFoundException: /external/images/media/24097: open failed: ENOENT (No such file or directory)
04-12 12:43:02.688 29890-29890 / com.example.prakash.eduqueri I / Adreno-EGL :: EGL 1.4 QUALCOMM build:AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.154.004_msm8226_LNX。 LA.3.5.2.2.2_RB1__release_AU() OpenGL ES着色器编译器版本:E031.24.00.15 建造日期:2014年6月8日星期三 当地分公司:mybranch4057433 远程分支:quic / LNX.LA.3.5.2.2.2_rb1 本地补丁:无 重建分支:AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.154.004 + NOTHING 04-12 12:43:02.848 29890-29890 / com.example.prakash.eduqueri I / Timeline:Timeline:Activity_idle id:android.os.BinderProxy@424bdc50 time:262597724
答案 0 :(得分:1)
如果当前片段在另一个片段内且片段在活动内部,则首先需要在父片段或活动中定义onActivityResult,然后首先在父片段和父Activty中定义onResultActivity。我猜是很可能(因为你正在使用viewPager)你的片段在一些片段内,而那个父片段在一个活动中,所以按照以下步骤:
首先在Activity中定义onActivityResult,然后在片段中定义你正在使用相机意图的片段。
root父Activity中的onActivityResult。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
在子片段中:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
} super.onActivityResult(requestCode, resultCode, data);
}
注意:如果你的相机意图片段在这个频段内,那么只有你必须这样做才能跳过这一步。
现在终于在cameraIntent片段中实现onActivityResult:
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == HomeActivity.RESULT_OK) {
try{
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView.setImageBitmap(bitmap); } catch (NullPointerException e) {
e.printStackTrace();
} }
} else if (resultCode == HomeActivity.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();
}
}
当相机意图开始时,在onClick of按钮中初始化fileUri变量。
最后,在启动相机意图时,您必须使用getParentFragment().startActivityForResult(intent,yourrequestCode);
所以你的明星意图如下:
btnCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String fileName = System.currentTimeMillis()+".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
fileUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getParentFragment().startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
在上面的方法中,fileUri是一个String类型变量,在方法之外定义,因为它应该用于设置图像的预览,如onActivityResult()
所示希望这会有所帮助,如果你有任何问题做评论,我会帮助你:) Have a happy codeing :)
答案 1 :(得分:0)
试试这个,
点击按钮添加此代码。
int TAKE_OR_PICK = 1;
Intent takePictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
覆盖onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == getActivity().RESULT_OK && null != data && TAKE_OR_PICK == 1) {
imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo)
if (imageBitmap != null) {
try {
long fileName = System.currentTimeMillis();
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + fileName + ".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
imageBitmap=Bitmap.createScaledBitmap(imageBitmap, 300, 300, true);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
File imageFile = new File(Environment.getExternalStorageDirectory() +File.separator + "photo_" + fileName + ".jpg");
picturePath = imageFile.getPath();
System.out.println("FILE PATH -> "+picturePath);
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}
}