相机崩溃应用程序后的操作

时间:2016-04-27 18:15:03

标签: java android camera

捕获图片后,我想更改片段,但应用程序只会崩溃。代码的Import和部分是最后的。感谢任何提示或解决方案。因为我是Java(android)开发的新手,我不知道,我的错在哪里。

这是我的代码:

setlocale

崩溃报告:

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;

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

        main newFragment = new main();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setImageResource(R.drawable.ic_menu_camera_light);

        int color = Color.parseColor("#FFFFFF");
        fab.setColorFilter(color);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                takePhoto();

            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            // super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_camera) {

            main newFragment = new main();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);
            transaction.commit();

        } else if (id == R.id.nav_gallery) {
            /*noVIP TextFragment = new noVIP();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, TextFragment);
            transaction.addToBackStack(null);
            transaction.commit();*/
            select_type TextFragment = new select_type();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, TextFragment);
            transaction.addToBackStack(null);
            transaction.commit();

        } else if (id == R.id.nav_manage) {
            Toast.makeText(MainActivity.this, "Nur Style ;)", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_share) {
            Toast.makeText(MainActivity.this, "Nur Style ;)", Toast.LENGTH_SHORT).show();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private static final int TAKE_PHOTO_CODE = 1;

    private void takePhoto() {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    private File getTempFile(Context context) {
        final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
        if (!path.exists()) {
            path.mkdir();
        }
        return new File(path, "image.tmp");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO_CODE:
                    final File file = getTempFile(this);
                    try {
                        Bitmap captureBmp = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));

                        HaveTakePhoto(); //Call the Fragment Change.

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    void HaveTakePhoto() { //<--- Called after the Picture has taken.
        noVIP TextFragment = new noVIP();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, TextFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        //Toast.makeText(MainActivity.this, "Do Stuff", Toast.LENGTH_SHORT).show();
    }
}

noVIP片段:

04-27 20:27:20.774 26944-26944/android.niklasvlach.simplegerman E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: android.niklasvlach.simplegerman, PID: 26944
                                                                                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {android.niklasvlach.simplegerman/android.niklasvlach.simplegerman.MainActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                                                                                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3607)
                                                                                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650)
                                                                                      at android.app.ActivityThread.access$1400(ActivityThread.java:154)
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:135)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                   Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                                                                                      at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1493)
                                                                                      at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1511)
                                                                                      at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
                                                                                      at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
                                                                                      at android.niklasvlach.simplegerman.MainActivity.HaveTakePhoto(MainActivity.java:165)
                                                                                      at android.niklasvlach.simplegerman.MainActivity.onActivityResult(MainActivity.java:148)
                                                                                      at android.app.Activity.dispatchActivityResult(Activity.java:6192)
                                                                                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3603)
                                                                                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650) 
                                                                                      at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370) 
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                      at android.os.Looper.loop(Looper.java:135) 
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5294) 
                                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                                      at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 

PS:如果我每隔一段时间使用此代码更改片段,应用程序就不会崩溃。

1 个答案:

答案 0 :(得分:0)

调用commitAllowingStateLoss()更像是一个hack而不是修复。国家损失很严重,应该不惜一切代价避免。在调用onActivityResult()时,活动/片段的状态可能尚未恢复,因此在此期间发生的任何事务都将因此而丢失。这是一个非常重要的错误,必须解决! (请注意,只有当你的Activity被系统杀死后才会出现这个错误...这取决于设备有多少内存,有时候很少见......所以这种bug不是那种在测试时非常容易捕获。)

尝试将事务移动到onPostResume()(请注意,onResume()之后始终调用onPostResume(),并且在onActivityResult()之后始终调用onResume()):

private boolean mReturningWithResult = false;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mReturningWithResult = true;
}

@Override
protected void onPostResume() {
    super.onPostResume();
    if (mReturningWithResult) {
        // Commit your transactions here.
    }
    // Reset the boolean flag back to false for next time.
    mReturningWithResult = false;
}

有关详细信息,请访问Fragment Transactions & Activity State Loss