(Sorry for changing the whole question as I found the actual problem after troubleshooting)I have my activity as followed:
public class MyAppActivity extends AppCompatActivity{
#Override
protected void onCreate(...)
{
//...
this.setContentView(contentViewResID);
Toolbar toolbar = (Toolbar) this.findViewById(toolbarResID);
this.setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onPause() {...}
#Override
protected void onResume() {...}
#Override
public boolean onSupportNavigateUp() {
Log.d("onSupportNavigateUp()", "pressed");
finish();
return super.onSupportNavigateUp();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == menuAddFood) {
Intent intent = new Intent(this, ActivityAddFood.class);
this.startActivity(intent);
}
if (item == menuSettings){
Intent intent = new Intent(this, ActivitySetting.class);
this.startActivity(intent);
}
if(item == menuUsername){
}
return true;
}
}
EDIT:
After my troubleshooting, I found out after override the onOptionsItemSelected(), onSupportNavigateUp() no longer fired anymore when I pressed the top left BACK / UP / HOME button. I want to do finish() inside onSupportNavigateUp() How to solve this?
You have to override the method in your current Activity and call the super:
public class ActivityExample extends MyAppActivity {
Context context = this;
AppCompatActivity activity = this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createMyView(R.layout.activity_log_in, R.id.toolbar);
// ...
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
Also, if you override onOptionsItemSelected, then onSupportNavigateUp will not be called.
//DONT OVERRIDE THIS METHOD
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
}
return true;
}
I am building an OpenGL live wallpaper. I decided to have a Navigation Drawer in my main activity since there are a lot of features the user will have access to.
The problem/issue
If I press the "hardware" back button to normally close an app the initial fragment that is shown just refreshes and the app never closes. If I hit the home button and go back to the app everything is a black screen. I've searched all throughout Google thinking that maybe I wasn't destroying the MainActivity properly or for a way to terminate a fragment. I've tried calling finish() in the main activity's onDestroy method. I've tried utilizing the remove method from fragment manager in each fragments onDetach method per posts that I've found online. Nothing has worked. I'm stumped. I've set debug points in the main activity on the onDestroy method and on the fragments onDetach method with no error being produced or any information being given. At this point I am clueless. Here's my MainActivity class.
public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
TextView usrTag, tagrEmail;
CircleImageView tagrPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
usrTag = (TextView)header.findViewById(R.id.usrName);
tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);
Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));
usrTag.setText(getUserName(getBaseContext()));
tagrEmail.setText(getUserEmail(getBaseContext()));
GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);
}
#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 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) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragmentClass = PreviewFragment.class;
} else if (id == R.id.nav_custom) {
startCustomLabelCreator();
} else if (id == R.id.nav_mylabels) {
} else if (id == R.id.nav_commLabels) {
fragmentClass = PostsFragment.class;
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCustomLabelCreator(){
Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
startActivity(cLC);
}
#Override
public void onPostComment(String postKey) {
}
#Override
public void onPostLike(String postKey) {
}
#Override
public void onPhotoSelected(String photoUrl) {
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
My Fragments
public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance() {
PostsFragment fragment = new PostsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
Query allPostsQuery = FirebaseUtil.getPostsRef();
mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
// TODO: Refresh feed view.
}
});
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
// FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
Log.d(TAG, post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
#Override
public void savePhotoUrl() {
//mListener.onPhotoSelected(post.getFull_url());
showLabelConfirm(post.getFull_url());
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
#Override
public void onSelectedPhoto(String selectPhoto) {
mListener.onPhotoSelected(selectPhoto);
}
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
void onPhotoSelected(String photoUrl);
}
private void showLabelConfirm(String uriBmp) {
FragmentManager fm = getFragmentManager();
PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
// SETS the target fragment for use later when sending results
editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
editNameDialogFragment.show(fm, "fragment_edit_name");
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Second Fragment:
public class PreviewFragment extends RajBaseFragment {
#Override
public ISurfaceRenderer createRenderer() {
return new PreviewRenderer(getContext());
}
}
Which extends:
public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {
protected FrameLayout mLayout;
protected ISurface mRajawaliSurface;
protected ISurfaceRenderer mRenderer;
public RajBaseFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the view
mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);
mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();
// Find the TextureView
mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);
// Create the loader
mRenderer = createRenderer();
onBeforeApplyRenderer();
applyRenderer();
return mLayout;
}
protected void onBeforeApplyRenderer() {
}
protected void applyRenderer() {
mRajawaliSurface.setSurfaceRenderer(mRenderer);
}
#Override
public void onClick(View v) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mLayout != null)
mLayout.removeView((View) mRajawaliSurface);
}
#Override
public int getLayoutID() {
return R.layout.rajawali_textureview_fragment;
}
}
I've tried all the recommendations below so far and the primary fragment that is set in the MainActivity's onCreate method still gets refreshed/reloaded when the back button is pressed rather than the app exiting/closing.
In your onNavigationItemSelected method, you are replacing the current fragment with fragment even in cases where fragment is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
with this one:
if (fragmentClass != null) {
fragment = fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish in the onDestroy method, which probably is not causing the problem but should be taken out because it does not make any sense there.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with addToBackStack, this allows back
navigation for added fragment.Because of fragment in backstack,
empty(black) activity layout will be displayed.
Change onBackPressed() as below which automatically close app after if no any Fragment found in FragmentManager:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
}
}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
Fragment pressing back button
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.
Try this code, hope this helps you, take necessary stuffs which are required for you. Also, try running this project in Android studio, it works.
https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java
When user press to back button it'll check fragment manager's backstack and if backstack entity count is bigger than 0 (this means there's a fragment in backstack) it'll popBackStack else it'll finish activity.
If you add your initial fragment to backstack, when user press back button they'll see a blank screen.
Also when you init your activity if you need to put a fragment it's a best practice to check if saved instance state is null. Here i modified some part of your code.
if(savedInstanceState == null){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}
I hope this'll help you. If you still have problem let me know.
Good luck.
create subclass for ISurface and override onKeyDown method like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Custom View", "onKeyDown");
//return super.onKeyDown(keyCode, event);
return false;
}
Could be related with the lifecycle...
Try using GLSurfaceView. I believe is easier for what you want, is special for OpenGL rendering and there is plenty information about it. Examples, lifecycle among others. Let me know if helped. If not, please, provide more info.
I am doing A Level computing and I'm trying to make an app for my Comp 4 project. All the other classes i have done with buttons seem to be working fine but the buttons on my main menu are not working.
public class MainActivity extends AppCompatActivity {
Button bLogin;
Button bProducts;
EditText etName, etAge, etUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
break;
case R.id.bProducts:
break;
}
return super.onOptionsItemSelected(item);
}
public void ProductsOnClick(View b) {
startActivity(new Intent(".Products"));
switch (b.getId()) {
case R.id.bProducts:
}
}
public void LoginOnClick(View a) {
startActivity(new Intent(".Login"));
switch (a.getId()){
case R.id.bLogin:
}
}
}
This Activity runs but the buttons on the Options Menu don't work.
I am using Android Studio to program this.
Because there is nothing to execute when the menu item is selected, change your code like that:
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
startActivity(new Intent(".Login"));
break;
case R.id.bProducts:
startActivity(new Intent(".Products"));
break;
}
return super.onOptionsItemSelected(item);
}
PS:
Make sure that you're using the right Intent constructor, because with Intent(String) you need an action as parameter not an activity name or something else.
You can use OnClickListener instead. Put this in your onCreate:
bProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Products"));
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Login"));
}
});
I have a question for my code, it should change the background color of my Start-Activity. I should choose between blue and red with radio buttons (in Radiogroup). I always get this error:
Error:(8, 8) error: com.example.clecks.reaction_game.OnCheckedChangeListener is not abstract and does not override abstract method onCheckedChanged(CompoundButton,boolean) in android.widget.CompoundButton.OnCheckedChangeListener
C:\Users\clecks\Desktop\asdfasdf\app\src\main\java\com\example\clecks\reaction_game\OnCheckedChangeListener.java
When I click on the error message there opens a new class named
OnCheckedChangeListener.java :
public class OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {}
Here is my code:
public class activity_settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_settings);
colorchange();
}
public void colorchange() {
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
final RadioButton changeToBlue = (RadioButton) findViewById(R.id.button_blue);
final RadioButton changeToRed = (RadioButton) findViewById(R.id.button_red);
final Button button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
changeOption(background);
}
});
changeToBlue.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changeToBlue(background);
}
});
changeToRed.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changeToRed(background);
}
});
}
public void changeOption(RelativeLayout background) {
if (background.isEnabled()) {
background.setEnabled(false);
} else {
background.setEnabled(true);
}
}
public void changeToBlue(RelativeLayout background) {
background.setBackgroundColor(0x0000FF00);
background.invalidate();
}
public void changeToRed(RelativeLayout background) {
background.setBackgroundColor(0x0000FF00);
background.invalidate();
}
#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_activity_settings, 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);
}}
CompoundButton itself is an abstract class (extending `Button).
You should not have CompoundButton in your activity_activity_settings layout.
Use Button for example instead.
public class MainActivity2 extends ActionBarActivity {
private static final String TAG = "Test Opencv Loadback";
public static String imgPath;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
//get path from Intent
imgPath = intent.getStringExtra(MainActivity.PATH_NAME);
//view image using setbitmap
}
#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_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, mLoaderCallback);
}
}
The status value is getting set to 2, even though the OpenCV manager is installed on the phone. Need help in resolving the issue.When prompted to install opencv manager, it returns package installation failed
Well I figured it out myself. This was because the version code in initAsnyc was set to OPENCV_VERSION_2_4_10 whereas the openCV manager version was 2.4.9. So changed the version in initAsync to OPENCV_VERSION_2_4_9.