如何在摄像头捕获后修复我的应用程序崩溃?

时间:2016-12-15 10:11:59

标签: android android-camera

我的应用程序从相机拍摄照片并将其显示给另一个活动。此外,还需要从Firebase存储和检索数据。

但是,在拍摄照片后应用程序崩溃并从相机中单击“确定”。 此外,我没有得到log cat异常。该怎么办? //以下是调用摄像机的活动:

HomeActivity.java

public class HomeActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private static final int CAMERA_REQUEST = 1888;
    private ViewPager mViewPager;
    private File imageFile;
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {

            String timeStamp= new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName="IMAGE_"+timeStamp+"_";

            //Adding Camera Intent when clicked on the FAB
            @Override
            public void onClick(View view) {
                Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent,CAMERA_REQUEST);
            }
        });
    }

    //What Happens After the Image is Captured
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==CAMERA_REQUEST && resultCode==Activity.RESULT_OK){
                Toast.makeText(this,"File saved to"+imageFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                Intent intent=new Intent(HomeActivity.this,PostActivity.class);
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                Uri uri=data.getData();
                intent.putExtra("EXTRA_VALUE",photo);
                intent.setData(uri);
                startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

SectionsPagerAdapter.java

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               AllPosts allposts=new AllPosts();
               return allposts;
           case 1:
               MyPosts myposts=new MyPosts();
               return myposts;
           default:
               return null;
       }
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "All Posts";
            case 1:
                return "My Posts";

         }
        return null;
       }
   }
}

以下是图像应在imageview中显示的代码

PostActivity.java

public class PostActivity extends Activity {

    private ImageButton mImageSelect;
    private EditText postTitle;
    private EditText postDescription;
    private Button submitButton;
    private TextView changeImage;
    private Uri imageUri=null;
    private StorageReference storage;
    private ProgressDialog progressDialogue;
    private DatabaseReference database;
    public  String titleVal;
    public String descriptionVal;
    private ImageView mImageView;
    private static final int GALLERY_REQUEST=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        storage= FirebaseStorage.getInstance().getReference();
        database= FirebaseDatabase.getInstance().getReference().child("Posts");

        mImageView=(ImageView) findViewById(R.id.imageView);

        postTitle=(EditText) findViewById(R.id.titleField);
        postDescription=(EditText)findViewById(R.id.descriptionField);
        submitButton=(Button) findViewById(R.id.submitPost);

        progressDialogue=new ProgressDialog(this);

        Intent intent=getIntent();
        Bitmap bitmap = (Bitmap) intent.getParcelableExtra("EXTRA_VALUE");
        imageUri=getIntent().getData();
        mImageView.setImageBitmap(bitmap);

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPosting();
            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("titleVal", titleVal);
        outState.putString("descriptionVal",descriptionVal );
    }

    private void startPosting() {
        titleVal=postTitle.getText().toString().trim();
        descriptionVal=postDescription.getText().toString().trim();

        if(!TextUtils.isEmpty(titleVal) && !TextUtils.isEmpty(descriptionVal) && imageUri!=null){
            progressDialogue.setMessage("আপলোড হচ্ছে......");
            progressDialogue.show();

            StorageReference filePath=storage.child("post_images").child(imageUri.getLastPathSegment());
            filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl=taskSnapshot.getDownloadUrl();
                    Picasso.with(PostActivity.this).load(downloadUrl).into(mImageView);
                    DatabaseReference newPost=database.push();
                    newPost.child("title").setValue(titleVal);
                    newPost.child("description").setValue(descriptionVal);
                    newPost.child("image").setValue(downloadUrl.toString());

                    progressDialogue.dismiss();
                    Toast.makeText(getApplicationContext(), "Successfully Uploaded", Toast.LENGTH_LONG).show();

                    startActivity(new   Intent(PostActivity.this,HomeActivity.class));
                }
            });

        }else{
            Toast.makeText(getApplicationContext(), "Please provide a Title", Toast.LENGTH_LONG).show();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用相机拍照时,您的数据始终为空。

尝试按以下方式开始活动:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String path;
if (Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED)) {
    path = Environment.getExternalStorageDirectory() + "/appdir";
} else {
    path = activity.getCacheDir() + "/appdir";
}
String filePath = path + "/image.jpg";
Uri imageUri = Uri.fromFile(new File(filePath));
intent.putExtra(MediaStore.EXTRA_OUTPUT, StaticStorage.selectedImageFromCamera);
activity.startActivityForResult(intent, requestCode);

在onActivityResult()上,您可以从StaticStorage.selectedImageUri

中检索捕获的图像Uri

答案 1 :(得分:0)

请尝试以下代码可能对您有所帮助。

首先声明一个变量

private static final int PICK_CAMERA_IMAGE = 2;
private Uri imageCaptureUri;

然后在按钮单击或onCreate()

上添加以下代码
Intent intent = new ntent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory()
                        + "/imgDirectory", "imgName"+ ".png");

                imageCaptureUri= Uri.fromFile(file);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
                startActivityForResult(intent, PICK_CAMERA_IMAGE);

并在onActivityResult中从imageCaptureUri获取图像并在imageview中显示图像。

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

            case PICK_CAMERA_IMAGE:                    
                img.setImageURI(imageCaptureUri);
                break;
        }
    }

如果要将URI从一个活动发送到另一个活动,可以使用intent发送此URI。 在onActivityResult中使用以下代码

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("imageUri", imageCaptureUri.toString());
startActivity(intent);

而不是

img.setImageURI(imageCaptureUri);.

然后在另一个活动中转换回这样的字符串,并将新创建的uri设置为imageview。

 Uri newUri = Uri.parse(getIntent().getStringExtra("imageUri"));
 ImageView img = (ImageView) findViewById(R.id.imageView);
 img.setImageURI(newUri);