My MainActivity is not calling onActivityResult after coming back from another activity using the onSupportNavigateUp method. I know that onSupportNavigateUp is working cause I logged it.
But when the MainActivity is returning i do not get the Log("RESULT") test, so it's not even getting to the if statement.
look at my code below
UPDATE: I've noticed a weird behaviour when pressing back button while on MainActivity. There seems to be multiple instances of it (like 8 or 10) before getting out of the app.
UPDATE: Joined my Manifest
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager mManager = getSupportFragmentManager();
FirebaseUser mCurrentUser;
FirebaseAuth mAuth;
private TextView mEmailHeader;
private User mUser;
private DatabaseReference mDatabase;
private static final int REQUEST_CODE = 222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
initializeViews();
mUser = new User();
mAuth = FirebaseAuth.getInstance();
if (mAuth != null) {
mCurrentUser = mAuth.getCurrentUser();
String email = mCurrentUser.getEmail();
mEmailHeader.setText(email);
mUser.setEmail(email);
writeNewUser(mCurrentUser.getUid(), mUser);
}
}
private void writeNewUser(String userId, User user) {
mDatabase.child("users").child(userId).setValue(user);
}
private void initializeViews() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyUtilty.showSnackbar(view, "Replace with your own action !");
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
mEmailHeader = headerView.findViewById(R.id.textViewEmailHeader);
}
#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) {
// 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
switch (id) {
case R.id.action_logout:
FirebaseAuth.getInstance().signOut();
finish();
return true;
case R.id.action_profile:
Intent intent = new Intent(this, ProfileActivity.class);
```startActivityForResult(intent, REQUEST_CODE);
return true;```
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_trips) {
MyUtilty.switchFragment(mManager, new TripsFragment());
} else if (id == R.id.nav_gallery) {
MyUtilty.switchFragment(mManager, new GalleryFragment());
} else if (id == R.id.nav_tips) {
} else if (id == R.id.nav_map) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("RESULT", "TEST");
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data != null && data.hasExtra("name")) {
String[] array = data.getStringArrayExtra("name");
mUser.setFirstName(array[0]);
mUser.setLastName(array[1]);
writeNewUser(mCurrentUser.getUid(), mUser);
Log.d("TEST", "It's working");
}
}
}
}
}
ProfileActivity
public class ProfileActivity extends AppCompatActivity {
private EditText mFirstName;
private EditText mLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initializeViews();
}
private void initializeViews() {
mFirstName = findViewById(R.id.editTextFirstName);
mLastName = findViewById(R.id.editTextLastName);
}
#Override
public boolean onSupportNavigateUp() {
Log.d("NAV_UP", "Nav up working");
String firstName = mFirstName.getText().toString();
String lastName = mLastName.getText().toString();
String[] array = {firstName,lastName};
Intent intent = new Intent();
intent.putExtra("name", array);
setResult(RESULT_OK,intent);
finish();
return super.onSupportNavigateUp();
}
}
Manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".ProfileActivity"
android:parentActivityName=".MainActivity"
android:label="Profile"></activity>
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignupActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" />
</application>
</manifest>
try to replace new Intent() with getIntent() - else there will be no REQUEST_CODE.
#Override
public boolean onKeyDown(int keyCode, #NonNull KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = this.getIntent();
String firstName = mFirstName.getText().toString();
String lastName = mLastName.getText().toString();
if(firstName != null && lastName != null) {
intent.putExtra("name", new String[] {firstName, lastName});
this.setResult(RESULT_OK, intent);
} else {
this.setResult(RESULT_CANCELED, intent);
}
this.finish();
}
return super.onKeyDown(keyCode, event);
}
I moved my code to a button instead of using onSupportNavigateUp().
For some reason onSupportNavigateUp does not support carrying out intents
public void onSave(View view) {
String firstName = mFirstName.getText().toString();
String lastName = mLastName.getText().toString();
String[] array = {firstName,lastName};
Intent intent = this.getIntent();
intent.putExtra("name", array);
this.setResult(RESULT_OK, intent);
this.finish();
}
Related
When I click on the back button, my MainActivity reopens. Why is this happening?
I integrated navigation-drawer in my MainActivity, and after this, when I click on the back button, the MainActivity is recreated. If I click again on the back button, the application gets closed.
This is my MainActivity code:
public class BuildingsActivity extends AppCompatActivity implements BuildingsNavigator,
BuildingItemNavigator, NavigationView.OnNavigationItemSelectedListener {
private ActivityBuildingsBinding binding;
private BuildingsViewModel viewModel;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_buildings);
viewModel = new BuildingsViewModel(this);
viewModel.loadBuildings();
viewModel.dataLoading.set(true);
if (!AppUtils.isOnline()) {
startForResult();
}
binding.setViewModel(viewModel);
binding.recycler.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
binding.recycler.setAdapter(new BuildingAdapter(new ArrayList<Building>(0), this, this));
drawerLayout = binding.drawer;
toolbar = binding.actionToolbar;
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navigationView = binding.buildingNavigation;
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.building_nav_item:
break;
case R.id.delivery_nav_item:
Intent deliveryIntent = new Intent(this, new DeliveryActivity().getClass());
startActivity(deliveryIntent);
item.setChecked(false);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Any suggestions?
Try to add to manifest: android:noHistory="true"
<activity android:name=".MainActivity"
android:screenOrientation = "portrait"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
or you can write handler for this button
#Override
public void onBackPressed() {
//add what you need, for example if you want to start another activity:
Intent intent = new Intent(AnotherActivity.this, MainActivity.class);
//or if you want to close:
this.finish();
//or
finish();
}
or if you about button on ActionBar you can write it in menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item:
//something
return true;
case android.R.id.home:
//what you need
return true;
}
return super.onOptionsItemSelected(item);
}
the Previous Activity you are coming from Has a code that it sending it back to the current activity you are in, in its onstart() method. try finishing the previous activity before entering the current one
#Override
protected void onStart() {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mFirebaseUser != null) {
Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mIntent);
}
super.onStart();
}
Try finishing the Activity after the Authentication
#Override
protected void onStart() {
FirebaseUser mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mFirebaseUser != null) {
Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mIntent);
finish();
}
super.onStart();
}
here is my java code
that is the java code, I have added navigation profile activity then run it after retrieving the image and user name from the firebase. the navigation buttons are no more clickable
public class OwnerDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth OwnerAuth;
private DatabaseReference OwnerRef;
private CircleImageView OwnNavProfileImge;
private TextView OwnNavProfileName;
String currentUserID;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OwnerAuth = FirebaseAuth.getInstance();
OwnerRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = OwnerAuth.getCurrentUser().getUid();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//for the navigation drawer button to open and close
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.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View navView = navigationView.inflateHeaderView(R.layout.nav_header_owner_drawer);
OwnNavProfileName = (TextView)navView.findViewById(R.id.NavOwnerUserName);
OwnNavProfileImge = (CircleImageView)navView.findViewById(R.id.NavOwnerProfileImage);
OwnerRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists()) {
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
OwnNavProfileName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(OwnerDrawer.this).load(image).placeholder(R.drawable.profile).into(OwnNavProfileImge);
}
else
{
Toast.makeText(OwnerDrawer.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = OwnerAuth.getCurrentUser();
if(currentUser == null)
{
SendUserTologinActivity();
}
else
{
CheckUserExistence();
}
}
// to see if the user validation and his authenticated so if not, the user will be send to the setup activity.
private void CheckUserExistence()
{
final String current_user_id = OwnerAuth.getCurrentUser().getUid();
OwnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(OwnerDrawer.this, OwnerSetup.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserTologinActivity() {
Intent loginIntent = new Intent(OwnerDrawer.this,OwnerLogin.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// To open the menu button
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Home) {
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Profile) {
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Posting_Cars) {
Toast.makeText(this, "Post Cars", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Chat) {
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Edit_profile) {
Toast.makeText(this, "Edit Profile", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.nav_Logout) {
OwnerAuth.signOut();
SendUserTologinActivity();
Toast.makeText(OwnerDrawer.this, "Logged Out Successfull...", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
To receive callbacks when the user taps a list item in the drawer, implement the OnNavigationItemSelectedListener and attach it to your NavigationView by calling setNavigationItemSelectedListener().
You need to attach the navigationView to listener
navigationView.setNavigationItemSelectedListener(this);
Hope this helps.
I am A Beginner in android development, actually I have a Navigation drawer with Fragments my issue is when i go to fragment b from a the state in navigation drawer is updating to fragment b successfully but when go to fragment B From Fragment A by on 'backpressed' method the drawer item state is not updating / changing to fragment A . please help me in fixing this.
Here is my Main Activity Code :
public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
//, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_PERMISSION = 10;
private Toolbar toolBar;
private NavigationView navDrawer;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private View btnLogOut;
private int selectedItem;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
// private GoogleApiClient googleApiClient;
private FloatingActionButton fab;
private CoordinatorLayout coordinatorLayout;
private HomeFragment homeFragment=new HomeFragment();
final String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String userID = user.getUid();
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
startActivity(intent);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_content, homeFragment);
tx.commit();
final WebView webView = (WebView) findViewById(R.id.WV);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here}
#Override
public void onReceivedError (WebView view,int errorCode, String description, String
failingUrl){
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("https://google.co.in");
requestAppPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
R.string.msg,REQUEST_PERMISSION);
toolBar =(Toolbar)
findViewById(R.id.app_bar);
setSupportActionBar(toolBar);
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if(
getIntent().
getExtras() !=null)
{
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
// subscribeToPushService();
drawerLayout =(DrawerLayout)
findViewById(R.id.drawer_layout);
navDrawer =(NavigationView)
findViewById(R.id.menu_drawer);
navDrawer.setNavigationItemSelectedListener(this);
drawerToggle =new
ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");
}
#Override
public boolean onNavigationItemSelected (MenuItem menuItem){
menuItem.setChecked(true);
selectedItem = menuItem.getItemId();
Fragment fragment = null;
switch (selectedItem) {
case R.id.nav_item_1:
fragment = new HomeFragment();
break;
case R.id.nav_item_2:
fragment = new MicrosoftDskFragment();
break;
case R.id.nav_item_3:
fragment = new GoogleDskFragment();
break;
case R.id.nav_item_4:
fragment = new AppleDskFragment();
break;
case R.id.nav_item_5:
fragment = new OthersDskFragment();
break;
case R.id.nav_item_6:
fragment = new MobiSpecsFragment();
break;
case R.id.nav_item_8:
Intent intent = new Intent(MainActivity.this, About.class);
startActivity(intent);
break;
default:
break;
}
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
} else {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_content, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
boolean twice = false;
#Override
public void onBackPressed () {
DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
Log.d(TAG, "click");
if (twice == true) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice: " + twice);
//super.onBackPressed();
Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice: " + twice);
}
}, 3000);
}
}
}
#Override
public boolean onKeyDown ( int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
homeFragment.OnKeyDown(keyCode);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#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, menu);
return super.onCreateOptionsMenu(menu);
}
#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.profile) {
Intent intent = new Intent(MainActivity.this, Profile.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("selectedItem", selectedItem);
}
#Override
public void onPermissionsGranted ( int requestCode){
//Do anything when permisson granted
// Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
/* #Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
*/
}
}
When you popBackStack() the fragment from back stack will appear on screen so you need to listen for Back stack changes.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null) {
// check for fragment and set the drawer state
if(fragment instanceof Frag1){
// set drawer state for 1
}else if(fragment instanceof Frag2){
// set drawer state for 2
}
}
}
});
I'm trying to detect the connection state of my app, but this is the Error am facing:
Failed to convert value of type java.util.HashMap to boolean
I am using Firebase. The error is on line:
boolean connected = dataSnapshot.getValue(Boolean.class);
So the Error comes in the OnDataFinishedLoading() method . Data was coming at first, but now I just want to detect the apps network connection. Below is my code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static String KEY_HEADLINES="headlines";
public static String KEY_DETAILS="details";
// private static final String TAG = "Ask Doctor App";
ProgressBar pb;
public List<NewsModel> newslist;
public NewsAdapter2 adapter;
private RecyclerView mRecyclerView;
private DatabaseReference mRef;
ImageView image_news;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call the array list
newslist = new ArrayList<NewsModel>();
pb = (ProgressBar) findViewById(R.id.progressBarNews);
image_news =(ImageView) findViewById(R.id.image_news);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Enabling offline capabilities
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// firebase initialisation......
mRef = FirebaseDatabase.getInstance().getReference("News");
// keep my data synced
mRef.keepSynced(true);
OnDataFinishedLoading();
// load data
//declare the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo netInfo = cm.getActiveNetworkInfo();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* if (isOnline()) {
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();
} else {
Snackbar.make(view, "There's a Network problem", Snackbar.LENGTH_LONG)
.setAction("", null).show();
}
Snackbar.make(view, "Refreshing news ....", Snackbar.LENGTH_LONG)
.setAction("Thanks.", null).show();*/
}
});
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void OnDataFinishedLoading(){
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if(connected) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LoadData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void LoadData (DataSnapshot dataSnapshot){
System.out.println(dataSnapshot.getValue());
NewsModel news_model =dataSnapshot.getValue(NewsModel.class);
newslist.add(news_model);
adapter = new NewsAdapter2(MainActivity.this, newslist);
mRecyclerView.setAdapter(adapter);
}
/* protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
*/
#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) {
// 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);
}*/
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.hospitals) {
i = new Intent(MainActivity.this, HealthCentres.class);
startActivity(i);
} else if (id == R.id.doctors) {
i = new Intent(MainActivity.this, Doctors.class);
startActivity(i);
} /*else if (id == R.id.location) {
i = new Intent(MainActivity.this, Location.class);
startActivity(i);
} */else if (id == R.id.tips) {
i = new Intent(MainActivity.this, Tips.class);
startActivity(i);
} /*else if (id == R.id.faq) {
}
*/
/*
else if (id == R.id.suggestions) {
}
*/
else if (id == R.id.contacts) {
i= new Intent(MainActivity.this, ContactUs.class);
startActivity(i);
}
/*
else if (id == R.id.settings) {
}
*/
else if (id == R.id.about) {
i = new Intent(MainActivity.this, AboutUs.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Ok, so the core problem you're having is that Firebase is returning a Map, not a Boolean. That's because of the way you have this configured--every time a child is added, you try to look at the DataSnapshot (that's what the listener you setup does), and tries to get a Boolean value out. However, the Snapshot is the child added to the database (and not a boolean) so instead you get a map out.
If all you want to do is verify that a child was added successfully, I'd do the following:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object value = dataSnapshot.getValue();
if(value != null) {
pb.setVisibility(View.INVISIBLE);
LoadData(dataSnapshot);
} else{
Toast.makeText(MainActivity.this,"No Network",Toast.LENGTH_LONG).show();
}
}
However, this isn't really going to solve your network connectivity problem. It'll just do stuff whenever a non-null child gets added to the firebase object, which could happen frequently. Also in LoadData, you don't check to make sure that the object passed in isn't null.
I'm trying to implement a splash screen on my app. After the loading of the splash screen, I have two issues.
If the user is connected, an activity is started. If not, an other is started.
But, with my implementation, when the user is connected, the splash screen is very long (8 or 9 sec), but I don't know why.
That is my first class which check if the user is connected, and it load some shared preferences? So maybe it's that?
public class AnnaActivity extends AppCompatActivity {
public PrefManager pref;
private AllRequest req;
private static final String REQUEST_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.pref = new PrefManager(getApplicationContext());
boolean isco = pref.getIsConnect();
if (isco) {
Log.e("SPLASH", "IsConnected");
Intent loginActivity = new Intent(this, NavigationDrawerActivity.class);
startActivity(loginActivity);
finish();
} else {
Log.e("SPLASH", "launch login activity");
Intent loginActivity = new Intent(this, MainActivity.class);
startActivity(loginActivity);
finish();
}
}
}
that is my splash drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryDark"/>
<item android:bottom="8dp"
android:top="8dp"
android:left="8dp"
android:right="8dp">
<bitmap android:gravity="center"
android:src="#mipmap/ic_launcher"
android:antialias="true"/>
</item>
</layer-list>
And my splach style
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_drawable</item>
</style>
(Edit post) The navigation drawerActivity
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Response.Listener, Response.ErrorListener{
public TextView TextViewEmailAddress;
public TextView TextViewLogin;
private PrefManager pref;
private AllRequest req;
public RequestQueue mQueue;
private static final String REQUEST_TAG = "LogOutActivity";
private String address;
private String login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
this.TextViewEmailAddress = (TextView)header.findViewById(R.id.textView_drawer_mail);
this.TextViewLogin = (TextView)header.findViewById(R.id.textView_drawer_login);
this.pref = new PrefManager(getApplicationContext());
this.req = new AllRequest(getApplicationContext());
this.mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
address = this.pref.getEmail();
login = this.pref.getLogin();
this.TextViewEmailAddress.setText(address);
this.TextViewLogin.setText(getText(R.string.text_view_login_drawer) + " " + login);
}
#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.navigation_drawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_mon_compte) {
Intent intent = new Intent(NavigationDrawerActivity.this, MyAccountActivity.class);
startActivity(intent);
} else if (id == R.id.nav_deconnection) {
deconnexion();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void deconnexion(){
LayoutInflater factory = LayoutInflater.from(this);
final View alertDialogView = factory.inflate(R.layout.alertdialog_logout, null);
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(alertDialogView);
adb.setTitle(R.string.alertDialod_logout_Title);
adb.setPositiveButton((R.string.alertDialog_logout_PositiveBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String accessToken = pref.getAccessToken();
req.revokeTokenRequest(REQUEST_TAG, accessToken, NavigationDrawerActivity.this, NavigationDrawerActivity.this);
pref.logout();
Intent intent = new Intent(NavigationDrawerActivity.this, MainActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton((R.string.alertDialog_logout_NegativeBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("errrrrrror :(", "it's not working");
}
#Override
public void onResponse(Object response) {
Log.e("pololololo","it's working :D");
}
}