在嵌套Fragment的onActivityResult中调用第二个Intent不会再次调用onActivityResult

时间:2017-01-09 17:27:24

标签: android android-fragments android-intent onactivityresult android-savedstate

我在一个嵌套片段中调用Camera意图,并在片段中的onActivityResult中获取图像,没有任何问题。由于我想裁剪图像,我在onActivityResult中调用(第二)意图将图像传递给裁剪意图。但是,在这种情况下不会调用onActivityResult(仅在应用程序在其中一个意图期间在后台终止时才相关)。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch (requestCode) {

        // Camera onActivityResult
        case INTENT_CAMERA:
            Toast.makeText(getActivity(), "IN CARD ONACTIVITY - CAMERA INTENT", Toast.LENGTH_LONG).show();
            if (resultCode == RESULT_OK) {

                SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
                String uriString = getPrefs.getString("photoUri", null);
                if (uriString != null) {

                    Uri selectedImage = Uri.parse(uriString);

                    Intent intent = CropImage.activity(selectedImage).setAspectRatio(1, 1).setMinCropResultSize(800, 800).getIntent(getContext());
                    startActivityForResult(intent, INTENT_CROP);

                } else {
                    Toast.makeText(getActivity(), "ERROR", Toast.LENGTH_LONG).show();
                }

            }
            break;

        // Crop ActivityOnResult
        case INTENT_CROP:
            Toast.makeText(getActivity(), "IN CARD ONACTIVITY - CROP INTENT", Toast.LENGTH_LONG).show();

            CropImage.ActivityResult result = CropImage.getActivityResult(imageReturnedIntent);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
                    uploadImage();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
    }
}

我在日志中找到以下行:

W/FragmentActivity: Activity result no fragment exists for who: android:fragment:0:1

仅在调用裁剪意图时抛出 - 而不是第一个摄像头意图。在调用第二个意图之前,我是否必须等待再次创建片段?或者还有其他可靠的方法来处理这种情况吗?谢谢!

活动代码:

public class MainActivity extends AppCompatActivity {

// Nav Drawer Variables
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;

private PrefManager prefManager;

FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = null;
FragmentTransaction transaction;
String FRAGMENT_TAG;


@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prefManager = new PrefManager(this);


    // Set a Toolbar to replace the ActionBar.
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Set navigation view
    NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
    View v = navigationView.getHeaderView(0);

    // Find drawer view
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = setupDrawerToggle();

    // Tie DrawerLayout events to the ActionBarToggle
    mDrawer.addDrawerListener(drawerToggle);

    // Find drawer view
    nvDrawer = (NavigationView) findViewById(R.id.nvView);
    // Setup drawer view
    setupDrawerContent(nvDrawer);


    //Set Progress Bar Invisible
    FrameLayout progressFrame = (FrameLayout) findViewById(R.id.progressFrame);
    progressFrame.setVisibility(View.GONE);



    // Switch between hamburger and back button
    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });
            } else {
                //show hamburger
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                drawerToggle.syncState();
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDrawer.openDrawer(GravityCompat.START);
                    }
                });
            }
        }
    });

    // Handle Fragments
    if (savedInstanceState != null) {

        fragment = fragmentManager.getFragment(savedInstanceState, "fragment");
        transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.flContent, fragment, FRAGMENT_TAG).commit();
    } else {
        // Insert the inital fragment
        Class fragmentClass = Fragment1.class;
        FRAGMENT_TAG = "FRAGMENT_1";
        try {
            fragment = (Fragment) fragmentClass.newInstance();

            transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.flContent, fragment, FRAGMENT_TAG).commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}


private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    return true;
                }
            });
}

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked

    Class fragmentClass = null;
    switch (menuItem.getItemId()) {
        case R.id.nav_home:
            FRAGMENT_TAG = "FRAGMENT_1";
            fragmentClass = Fragment1.class;
            break;
        case R.id.nav_mychallenges:
            FRAGMENT_TAG = "FRAGMENT_2";
            fragmentClass = Fragment2.class;
            break;
        case R.id.nav_feedback:
            FRAGMENT_TAG = "FRAGMENT_3";
            fragmentClass = Fragment3.class;
            break;
        default:
FRAGMENT_TAG = "FRAGMENT_1";
            fragmentClass = Fragment1.class;
    }
    try {
        fragment = (Fragment) fragmentClass.newInstance();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // Insert the fragment by replacing any existing fragment

    transaction = fragmentManager.beginTransaction();
    //transaction.addToBackStack(null);
    transaction.replace(R.id.flContent, fragment, FRAGMENT_TAG).commit();

    // Highlight the selected item has been done by NavigationView
    menuItem.setChecked(true);
    // Set action bar title
    setTitle(menuItem.getTitle());
    // Close the navigation drawer
    mDrawer.closeDrawers();
}

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


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE! Make sure to override the method with only a single `Bundle` argument
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();

}


@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    drawerToggle.onConfigurationChanged(newConfig);
}

@Override
protected void onResume() {
    super.onResume();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    fragmentManager.putFragment(outState, "fragment", fragmentManager.findFragmentById(R.id.flContent));
    Log.d("TAG", "CURRENT_FRAGMENT: " + fragmentManager.findFragmentById(R.id.flContent));
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

}

修改

ParentFragment:

public class FragmentProcess extends Fragment {


Fragment childFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {



    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_process, container, false);
    TextView processTitle = (TextView) view.findViewById(R.id.title);
    processTitle.setText("Title");
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    loadData();
}

private void loadData() {


        String url = "example.com ";
        // Instantiate the RequestQueue.
        // RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                subChallengesString = response;

                insertNestedFragment();


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);


}

// Embeds the child fragment dynamically
private void insertNestedFragment() {



    childFragment = new FragmentProcessChallengeCard();
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.replace(R.id.process_challenge_child_fragment, childFragment).commit();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //Save the fragment's state here
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    }
}

2 个答案:

答案 0 :(得分:0)

您需要将活动结果从您的活动传递给片段。

只需在<div ng-repeat="q in section"> {{q}} </div> 中试用此代码,然后检查它是否有效。

activity

答案 1 :(得分:0)

您正在使用的库已写入将调用父Activity的onActivityResult方法。检查您的onActivityResult of Parent Activity并创建一个方法或接口,将相同的结果发送到您的片段。

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
   CropImage.ActivityResult result = CropImage.getActivityResult(data);
   if (resultCode == RESULT_OK) {
       Uri resultUri = result.getUri();
   } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
       Exception error = result.getError();
   }
}