我想在片段中显示捕获的图像,但是没有显示,例如尽管片段中的回调代码似乎正在运行。
这是我的活动-
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Views and Context
private View nav_header_view;
private Context context;
// Widgets
private TextView tvCompanyName, tvCompanyEmail, tvName;
private ImageView imageView;
private ViewPager mViewPager;
public TabLayout tabLayout;
// Data
private FragmentManager manager;
private int selectNavId;
private ArrayList<Category> categoryArrayList = new ArrayList<>();
private String uuId = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
setTitle("Home");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
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) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
switch (selectNavId) {
case R.id.nav_search:
openSearchFragment();
break;
case R.id.nav_home:
displayTabForHomeFragment();
break;
case R.id.nav_daily_sales:
openDailySalesFragment();
break;
case R.id.nav_store:
openCompanyFragment();
break;
case R.id.nav_purchase:
openOrderedFragment();
break;
case R.id.nav_account:
openAccountFragment();
break;
case R.id.nav_logout:
logoutSession();
}
}
};
drawer.addDrawerListener(toggle);
toggle.syncState();
initializeUI();
checkUserSession();
}
private void initializeUI() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
nav_header_view = navigationView.getHeaderView(0);
tvName = (TextView) nav_header_view.findViewById(R.id.tv_name);
tvCompanyName = (TextView) nav_header_view.findViewById(R.id.tvCompanyName);
tvCompanyEmail = (TextView) nav_header_view.findViewById(R.id.tvEmail);
imageView = (ImageView) nav_header_view.findViewById(R.id.iv_profile_picture);
}
@Override
public void onResume() {
super.onResume();
refreshFragment();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof DailySalesFragment) {
closeSession();
} else {
// openHomeFragment();
openDailySalesFragment();
}
}
}
private void checkUserSession() {
String authToken = UserSession.getToken(this);
if (authToken.length() <= 0 && UserAccount.checkUserCount(context) > 0) {
openUserActivity();
} else if (authToken.length() <= 0) {
Intent login_intent = new Intent(this, LoginActivity.class);
startActivity(login_intent);
this.finish();
} else {
updateNavName(context);
openDailySalesFragment();
}
}
public void updateNavName(Context context) {
tvName.setText(UserSession.getFirstName(context) + " " + UserSession.getLastName(context));
tvCompanyName.setText(UserSession.getCompany(this));
tvCompanyEmail.setText(UserSession.getEmployeeEmail(this));
showProfilePic();
}
public void showProfilePic() {
// if (UserSession.getProfilePicture(context).contains("media")) {
// RequestOptions myOption = new RequestOptions().circleCrop();
// Glide.with(context).load(UserSession.getProfilePicture(context)).apply(myOption).into(imageView);
// }
}
private void logoutSession() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
UserSession.clearSession(context);
removeAllInCart();
checkUserSession();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
PopUpProvider.buildConfirmationDialog(context, dialogClickListener, "Confirm logout", "Are you sure you want to log out?");
}
private void closeSession() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
MainActivity.super.onBackPressed();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
PopUpProvider.buildConfirmationDialog(context, dialogClickListener, "Are you sure you want to close application?", null);
}
private void removeAllInCart() {
Checkout checkout = new Checkout();
checkout.deleteAll(context);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
selectNavId = id;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void refreshFragment() {
try {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof CompanyFragment) {
openCompanyFragment();
} else if (f instanceof OrderedFragment) {
openOrderedFragment();
} else if (f instanceof AccountFragment) {
openAccountFragment();
} else {
// openHomeFragment();
openDailySalesFragment();
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
private void openUserActivity() {
Intent intent = new Intent();
intent.setClass(context, UserAccountActivity.class);
startActivity(intent);
this.finish();
}
private void openHomeFragment(String uuid) {
Bundle bundle = new Bundle();
bundle.putString("uuid", uuid);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setArguments(bundle);
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, homeFragment, homeFragment.getTag()).commit();
}
private void openOrderedFragment() {
setTitle("My Purchases");
OrderedFragment orderedFragment = new OrderedFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, orderedFragment, orderedFragment.getTag()).commit();
}
private void openAccountFragment() {
setTitle("Account");
AccountFragment accountFragment = new AccountFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, accountFragment, "ACCOUNT_TAG").commit();
}
private void openCompanyFragment() {
setTitle("Store");
CompanyFragment companyFragment = new CompanyFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, companyFragment, companyFragment.getTag()).commit();
}
private void openDailySalesFragment() {
setTitle("Daily Sales");
DailySalesFragment dailySalesFragment = new DailySalesFragment();
manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main, dailySalesFragment, dailySalesFragment.getTag()).commit();
}
private void openSearchFragment() {
setTitle("Select Category");
replaceFragment(SearchFragment.class, null);
}
public void replaceFragment(Class fragmentClass, Bundle bundle) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
fragment.setArguments(bundle);
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, fragment).commit();
}
// Online functions
public void fetchCategory() {
try {
HttpClientProvider.get(context, "read_category/", null, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
}
@Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tabLayout.removeAllTabs();
categoryArrayList = new Gson().fromJson(response.getJSONArray("records").toString(), new TypeToken<ArrayList<Category>>() {
}.getType());
Category category = new Category();
category.setName("All");
categoryArrayList.add(0, category);
for (Category inventory : categoryArrayList) {
tabLayout.addTab(tabLayout.newTab().setText(inventory.getName()));
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Toasty.error(context, "Can't Connect to Server").show();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toasty.error(context, responseString).show();
}
@Override
public void onRetry(int retryNo) {
super.onRetry(retryNo);
}
@Override
public void onFinish() {
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
public void displayTabForHomeFragment() {
fetchCategory();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
for (int i = 0; i < categoryArrayList.size(); i++) {
if (position > 0) {
uuId = categoryArrayList.get(position).getUuId();
Bundle bundle = new Bundle();
bundle.putString("uuid", uuId);
openHomeFragment(uuId);
break;
} else {
openHomeFragment("");
break;
}
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
这是我的片段-
public class AccountFragment extends Fragment {
private static final int REQUEST_IMAGE_CAPTURE = 1;
// View and Context
private View view;
private Context context;
// Widget
private EditText tvFirstName, tvLastName, tvCode, tvEmail, tvEmployeeId;
private ImageView imageView;
private ProgressDialog progressDialog;
private Button btnUpdate, btnUpload;
private boolean updateSuccess = false;
//Data
private ArrayList<UserAccount> userAccountArrayList = new ArrayList<>();
private String mCurrentPhotoPath;
private Bitmap mImageBitmap;
// Handles Interface and Initialization Functions
// Parameters - Default
// Return - View mag display sa layout
public AccountFragment(){
super();
}
public static AccountFragment newInstance(int sectionNumber) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putInt("ARG_SECTION_NUMBER", sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
return view;
}
@Override
public void onStart() {
super.onStart();
setHasOptionsMenu(true);
context = getContext();
initializeUI();
}
// Initialize component from a layout file
private void initializeUI() {
tvFirstName = view.findViewById(R.id.tv_firstname);
tvLastName = view.findViewById(R.id.tv_lastname);
tvCode = view.findViewById(R.id.tv_code);
tvEmail = view.findViewById(R.id.tv_email);
tvEmployeeId = view.findViewById(R.id.tv_employee_id);
imageView = view.findViewById(R.id.iv_User);
btnUpdate = view.findViewById(R.id.btn_update);
btnUpload = view.findViewById(R.id.btn_UploadImage);
((MainActivity) context).tabLayout.setVisibility(View.GONE);
getUserProfile();
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateUserProfile();
}
});
// showProfilePic();
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
private void dispatchTakePictureIntent() {
Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent, REQUEST_IMAGE_CAPTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
private void showProfilePic() {
if (UserSession.getProfilePicture(context).contains("media")) {
RequestOptions myOption = new RequestOptions().circleCrop();
Glide.with(context).load(UserSession.getProfilePicture(context)).apply(myOption).into(imageView);
}
}
private void displayEmployeeDetails() {
tvFirstName.setText(UserSession.getFirstName(getContext()));
tvLastName.setText(UserSession.getLastName(getContext()));
tvCode.setText(UserSession.getEmployeeCode(getContext()));
tvEmail.setText(UserSession.getEmployeeEmail(getContext()));
tvEmployeeId.setText(UserSession.getYpoEmployeeId(getContext()));
// showProfilePic();
}
public void getUserProfile() {
try {
HttpClientProvider.get(context, "customer_profile/", null, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false); // disable dismiss by tapping outside of the dialog
progressDialog.show();
}
@Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
UserSession session = new Gson().fromJson(response.toString(), new TypeToken<UserSession>() {
}.getType());
session.saveUserSession2(context);
if (session.saveUserSession2(context)) {
displayEmployeeDetails();
((MainActivity) getActivity()).updateNavName(context);
}
if (updateSuccess) {
Toasty.success(context, "Update success", Toast.LENGTH_SHORT).show();
//Update account in database
String searchQuery;
searchQuery = " WHERE e_mail LIKE '%" + UserSession.getEmployeeEmail(context) + "%' ";
userAccountArrayList = UserAccount.read(context, searchQuery);
for (UserAccount userAccount : userAccountArrayList) {
userAccount.setFirstName(UserSession.getFirstName(getContext()));
userAccount.setLastName(UserSession.getLastName(getContext()));
userAccount.setEmail(UserSession.getEmployeeEmail(getContext()));
userAccount.setToken(UserSession.getToken(getContext()));
userAccount.save(context);
}
}
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Debugger.printO("JSONObject " + throwable.toString());
Toasty.error(context, "Server Error").show();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toasty.error(context, responseString).show();
}
@Override
public void onFinish() {
progressDialog.dismiss();
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
private void updateUserProfile() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("first_name", tvFirstName.getText().toString());
jsonObject.put("last_name", tvLastName.getText().toString());
jsonObject.put("code", tvCode.getText().toString());
jsonObject.put("ypo_employee_id", tvEmployeeId.getText().toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
HttpClientProvider.post(context, "customer_profile/", stringEntity, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false); // disable dismiss by tapping outside of the dialog
progressDialog.show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
super.onSuccess(statusCode, headers, response);
getUserProfile();
updateSuccess = true;
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Toasty.error(context, "Server Error").show();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Toasty.error(context, errorResponse.toString()).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toasty.error(context, responseString).show();
}
@Override
public void onFinish() {
progressDialog.dismiss();
}
});
} catch (Exception err) {
Toasty.error(context, err.toString()).show();
}
}
//Hide item in Action bar
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItem = menu.findItem(R.id.action_cart);
MenuItem quantityItem = menu.findItem(R.id.action_quantity);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
MenuItem menuRemove = menu.findItem(R.id.action_remove_all);
menuRemove.setVisible(false);
menuItem.setVisible(false);
quantityItem.setVisible(false);
searchViewItem.setVisible(false);
}
这是我的清单-
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera" android:required="true"/>
当我单击片段中的Camera Intent时,片段中的imageview不会改变。我不知道为什么会这样,因为它在一项活动中效果很好。
答案 0 :(得分:1)
在Activity.onResume ()
中,您最终呼叫openAccountFragment ()
。这样会创建一个新的片段,并在每次屏幕可见时运行。(顺便说一下,一个可能不相关的错误是您没有在此处调用newInstance()
。)
每次创建新片段时,都会删除旧片段。
但是您的回叫功能正在旧片段上发生,该片段不再连接或可见(请注意,此链接与Mike's comments关联)
解决方案是,如果您已经拥有正确的类型,则不要用新片段替换现有片段。
答案 1 :(得分:0)
将onActivityResult覆盖到MainActivity中。公开imageView并将imageView进入活动结果方法,如下所示。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_main);
if (f instanceof AccountFragment) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
f.imageView.setImageBitmap(photo);
}
}
}