Я вызываю намерение камеры во вложенном фрагменте и без проблем получаю изображение в onActivityResult во фрагменте. Поскольку я хочу обрезать изображение, я вызываю (второе) намерение в onActivityResult передать изображение в намерение Crop. Тем не менее, 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);
}
}
EDIT:
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);
}
}
Вы можете указать код своей деятельности? –
@JayminPanchal Я добавил код активности выше – mojo
, вы уверены, что правильно вызвали намерение cropImage? –