Everything is working fine but DatabaseReference is not fetching data, it's like just ignoring my code to run and like my internet is not working please help i'm new here in this community below are my codes and images.
Previously it was working, but as i just changed some code to make only currentVersion >= vCode so that user can continue even if the value in database is < currentVersion but, after building it my app was not fetching data from firebase and the i tried to uninstall it, installed again from play store the older version it also was not fetching data please help. I don't know what wrong i did. Thus i am planning to install ParrotOS so maybe then it'll work but it's better to ask first from the experts
firebase database image
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView appName;
FirebaseUser firebaseUser;
String currentVersionName;
long currentVersionCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appName = findViewById(R.id.appName);
currentVersionName = BuildConfig.VERSION_NAME;
currentVersionCode = BuildConfig.VERSION_CODE;
animateAppName();
netConn();
FirebaseAuth.getInstance();
}
public void applyScreenChange(){
String sharedPerfId = "MyAppPref";
SharedPreferences sharedPreferences = getSharedPreferences(sharedPerfId,0);
boolean isAdvertiserLoggedIn = sharedPreferences.getBoolean("isAdvertiserLoggedIn",false);
boolean isCreatorLoggedIn = sharedPreferences.getBoolean("isCreatorLoggedIn",false);
if (isAdvertiserLoggedIn){
skipSetupToAdvertiser();
}
else if (isCreatorLoggedIn){
skipSetupToCreator();
}
else {
newActivity();
}
}
public void animateAppName(){
appName.setTranslationY(-1000f);
appName.animate().translationYBy(1000f).setDuration(500);
}
public void netConn(){
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()){
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("Connect to Network and Then try again");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
netConn();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}else {
// Check older version
// applyScreenChange();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Version");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String vName = (String) snapshot.child("latestVersionName").getValue();
long vCode = (long) snapshot.child("latestVersionCode").getValue();
if (currentVersionName.equals(vName) && currentVersionCode >= vCode){
applyScreenChange();
// TODO: 16-08-2020 add condition to open app if version is higher
}else {
Toast.makeText(MainActivity.this, "Old Version", Toast.LENGTH_SHORT).show();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("You're on Older Version");
alertDialog.setMessage("This Version is no more supported, Kindly update your App to Continue");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_link))));
Toast.makeText(MainActivity.this, "Kindly Search Sponso on PlayStore and Update", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
public void newActivity(){
Intent intent = new Intent(MainActivity.this, AdvertiserCreatorChooser.class);
startActivity(intent);
finish();
}
public void skipSetupToAdvertiser(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, AdvertiserHome.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(MainActivity.this, AdvertiserLoginRegister.class);
startActivity(intent);
finish();
}
}
public void skipSetupToCreator(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, CreatorHome.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(MainActivity.this, CreatorLoginRegister.class);
startActivity(intent);
finish();
}
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.webroose.sponso">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:allowBackup="true"
android:theme="#style/AppTheme">
<activity android:name=".Advertiser.AdvertiserCampaignUpdate"/>
<activity android:name=".Advertiser.ui.main.AdvertiserSettings" />
<activity android:name=".Creator.CreatorRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserChatActivity" />
<activity android:name=".Creator.CreatorChatActivity" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="#string/app_id" />
<activity android:name=".Creator.CreatorUserDetails" />
<activity android:name=".Creator.CreatorList" />
<activity android:name=".Common.AboutUs" />
<activity
android:name=".AdvertiserHome"
android:label="#string/title_activity_advertiser_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Advertiser.AdvertiserLoginRegister"
android:label="#string/title_activity_advertiser_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Common.PrivacyPolicy" />
<activity android:name=".Common.ChangePassword" />
<activity android:name=".Creator.CreatorSettings" />
<activity android:name=".Common.ChangeEmail" />
<activity android:name=".Advertiser.AdvertiserUserDetails" />
<activity android:name=".Advertiser.AdvertiserList" />
<activity
android:name=".CreatorHome"
android:label="#string/title_activity_creator_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Creator.CreatorLoginRegister"
android:label="#string/title_activity_creator_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".AdvertiserCreatorChooser" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
dependency
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'com.google.android.material:material:1.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'androidx.navigation:navigation-ui:2.3.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.google.firebase:firebase-auth:19.3.2'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
implementation 'com.google.android.gms:play-services-ads:19.3.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.google.firebase:firebase-analytics:17.5.0'
implementation 'com.google.firebase:firebase-messaging:20.2.4'
implementation 'com.facebook.android:audience-network-sdk:5.10.1'
}
Change
DatabaseReference databaseReference =FirebaseDatabase.getInstance().getReference("Version");
To
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Version");
And the actual problem was with Firebase Database
Check below image with firebase database
Related
my app when I run it only shows the splash screen then crashes.
at first it was giving me "app keep on stopping" when I run it but now it runs the splash screen then crashes.
Splash screen.
public class SplashActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
private boolean mIsBackButtonPressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
sharedPreferences=getSharedPreferences(Constants.pref_name,MODE_PRIVATE);
new Handler().postDelayed(new Runnable() {
public void run() {
if (!mIsBackButtonPressed) {
if(getIntent().hasExtra("action_type")){
Intent intent= new Intent(SplashActivity.this, MainActivity.class);
String action_type=getIntent().getExtras().getString("action_type");
String receiverid=getIntent().getExtras().getString("senderid");
String title=getIntent().getExtras().getString("title");
String icon=getIntent().getExtras().getString("icon");
intent.putExtra("icon",icon);
intent.putExtra("action_type",action_type);
intent.putExtra("receiverid",receiverid);
intent.putExtra("title",title);
startActivity(intent);
finish();
}
else
GPSStatus();
}
}
}, 2000);
}
public void onBackPressed() {
// set the flag to true so the next activity won't start up
mIsBackButtonPressed = true;
super.onBackPressed();
}
public void GPSStatus(){
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!GpsStatus)
{
Toast.makeText(this, "On Location in High Accuracy", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),2);
}else {
GetCurrentlocation();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2){
GPSStatus();
}
}
private void GetCurrentlocation() {
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
enable_location();
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// if we successfully get the location of the user then we will save the locatio into
//locally and go to the Main view
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Constants.Lat,""+location.getLatitude());
editor.putString(Constants.Lon,""+location.getLongitude());
editor.commit();
startActivity(new Intent(SplashActivity.this, MainActivity.class));
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
}
else {
if(sharedPreferences.getString(Constants.Lat,"").equals("") || sharedPreferences.getString(Constants.Lon,"").equals("") ){
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Constants.Lat,"33.738045");
editor.putString(Constants.Lon,"73.084488");
editor.commit();
}
startActivity(new Intent(SplashActivity.this, MainActivity.class));
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
}
}
});
}
private void enable_location() {
EnableLlocationFragment enable_llocationFragment = new EnableLlocationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left,R.anim.in_from_left,R.anim.out_to_right);
getSupportFragmentManager().popBackStackImmediate();
transaction.replace(R.id.splash, enable_llocationFragment).addToBackStack(null).commit();
}
}
I believe it must be something with my MainActivity that is causing the problem,
this is the main activity code
main activity:
public class MainActivity extends AppCompatActivity {
long mBackPressed;
public static SharedPreferences sharedPreferences;
public static String user_id;
public static String user_name;
public static String image;
public static String image1;
public static String birthday;
public static String about;
public static String purchased;
public static String token;
BaseApp baseApp;
LinearLayout llsearch;
DatabaseReference rootref;
AboutModels modelAbout;
public static String title="none";
EditText search;
public static MainActivity mainActivity;
private FragmentManager fragmentManager;
BottomNavigationView navigation;
int previousSelect = 0;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
HomeFragment homeFragment = new HomeFragment();
navigationItemSelected(0);
loadFrag(homeFragment, getString(R.string.menu_home), fragmentManager);
llsearch.setVisibility(View.VISIBLE);
return true;
case R.id.property:
PropertyFragment propertyFragment = new PropertyFragment();
navigationItemSelected(1);
loadFrag(propertyFragment, getString(R.string.menu_property), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.favourite:
FavouriteFragment matchFragment = new FavouriteFragment();
navigationItemSelected(2);
loadFrag(matchFragment, getString(R.string.menu_favourite), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.chat:
MessageFragment messageFragment = new MessageFragment();
navigationItemSelected(3);
loadFrag(messageFragment, getString(R.string.menu_chat), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.user:
ProfileFragment profileFragment = new ProfileFragment();
navigationItemSelected(4);
loadFrag(profileFragment, getString(R.string.menu_profile), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
}
return false;
}
};
private BaseApp FirebaseInstanceId;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mAdViewLayout = findViewById(R.id.adView);
BannerAds.ShowBannerAds(getApplicationContext(), mAdViewLayout);
fragmentManager = getSupportFragmentManager();
llsearch = findViewById(R.id.llsearch);
baseApp = BaseApp.getInstance();
navigation = findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
modelAbout = new AboutModels();
HomeFragment homeFragment = new HomeFragment();
loadFrag(homeFragment, getString(R.string.menu_home), fragmentManager);
mainActivity =this;
sharedPreferences = getSharedPreferences(Constants.pref_name, MODE_PRIVATE);
user_id = sharedPreferences.getString(Constants.uid, "null");
user_name = sharedPreferences.getString(Constants.f_name, "") + " " + sharedPreferences.getString(Constants.l_name, "");
image =sharedPreferences.getString(Constants.u_pic,"null");
image1 =sharedPreferences.getString("image1","null");
token=sharedPreferences.getString(Constants.device_token, FirebaseInstanceId.getInstance().getToken());
rootref= FirebaseDatabase.getInstance().getReference();
search = findViewById(R.id.search);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String sSearch= search.getText().toString().trim();
if (TextUtils.isEmpty(sSearch)) {
Toast.makeText(MainActivity.this, "Column Can't be Empty", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
intent.putExtra("searchtext", sSearch);
startActivity(intent);
return true;
}
return false;
}
});
PackageInfo packageInfo = null;
try {
packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Constants.versionname=packageInfo.versionName;
}
#Override
protected void onStart() {
super.onStart();
if (baseApp.getIsLogin()) {
rootref.child("Users").child(user_id).child("token").setValue(token);
} else {
rootref.child("Users").child(user_id).child("token").setValue("null");
}
}
#Override
protected void onResume() {
super.onResume();
Check_version();
}
#Override
public void onBackPressed() {
int count = this.getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
if (mBackPressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
clickDone();
}
} else {
super.onBackPressed();
}
}
public void clickDone() {
new AlertDialog.Builder(this)
.setIcon(R.mipmap.ic_launcher)
.setTitle(getString(R.string.app_name))
.setMessage("Are you sure you want to exit?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
public void Check_version(){
VersionChecker versionChecker = new VersionChecker(this);
versionChecker.execute();
}
public void loadFrag(Fragment f1, String name, FragmentManager fm) {
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.Container, f1, name);
ft.commit();
}
public void navigationItemSelected(int position) {
previousSelect = position;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.otacodes.goestate">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="com.android.vending.BILLING" />
<application
android:name="com.otacodes.goestate.Constants.BaseApp"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-1300058369369222~7049892454"/>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.otacodes.goestate.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name="com.otacodes.goestate.Activity.SplashActivity"
android:screenOrientation="fullSensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.otacodes.goestate.Activity.LoginFormActivity"
android:screenOrientation="fullSensor"
android:theme="#style/Login_phone_A"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.RegisterActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropByCatActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPopularActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropByCityActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.SearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.MyPropertyActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.PropertyDetailActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.FilterSearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.PicklocationActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.MainActivity"
android:screenOrientation="portrait" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name="com.soundcloud.android.crop.CropImageActivity"
android:screenOrientation="portrait"
android:theme="#style/noActionBar"
/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_launcher" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/coloraccent" />
<service android:name="com.otacodes.goestate.Utils.NotificationReceive"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name="com.otacodes.goestate.Activity.AboutActivity" />
<activity android:name="com.otacodes.goestate.Activity.PrivacyActivity" />
<activity android:name="com.otacodes.goestate.Activity.BlockActivity" />
<activity android:name="com.otacodes.goestate.Activity.FullImageActivity" />
<activity android:name="com.otacodes.goestate.Activity.AddPropertyActivity" />
</application>
</manifest>
logcat
2022-01-05 01:50:49.624 4111-8222/? I/ExperimentPackageManage: Package com.google.android.os.statsd name not found! Using module version.
2022-01-05 01:50:49.626 4111-8222/? I/ExperimentPackageManage: Package com.google.android.os.statsd name not found! Using module version.
2022-01-05 01:50:49.631 4111-8222/? I/ayxc: updateFromConfigurations DeviceConfig for namespace virtualization_framework_native [CONTEXT service_id=204 ]
2022-01-05 01:50:49.572 3623-3623/? V/SettingsProvider: Notifying for 0: content://settings/config/app_standby/Phenotype_flags
2022-01-05 01:50:49.635 3623-3623/? V/SettingsProvider: Notifying for 0: content://settings/config/virtualization_framework_native/Phenotype_flags
2022-01-05 01:50:51.048 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.feedback.internal.IFeedbackService cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:52.610 1768-5915/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2022-01-05 01:50:52.787 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.mdd.service.START cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:53.138 4111-6600/? W/Nearby: Failed attempt #3 out of 3 for RestoreDeviceName [CONTEXT service_id=49 ]
java.lang.IllegalStateException: BluetoothAdapter not ready yet!
at aswl.d(:com.google.android.gms#214815031#21.48.15 (100700-414534850):2)
at aswj.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at cmvg.call(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at cmvl.a(:com.google.android.gms#214815031#21.48.15 (100700-414534850):2)
at cmvl.b(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at aswk.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):5)
at java.lang.Thread.run(Thread.java:919)
at xtk.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):5)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at xzm.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at java.lang.Thread.run(Thread.java:919)
2022-01-05 01:50:55.826 3623-3647/? E/memtrack: Couldn't load memtrack module
2022-01-05 01:50:55.826 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.common.download.START cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:55.826 3623-3647/? W/android.os.Debug: failed to get memory consumption info: -1
2022-01-05 01:50:55.869 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.ocr.service.internal.START cmp=com.google.android.gms/.chimera.GmsInternalApiService }
2022-01-05 01:50:55.974 7623-7658/? I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
2022-01-05 01:50:55.976 7623-7623/? I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
2022-01-05 01:50:55.979 7623-7623/? I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: VvmTaskReceiver - task received
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: VvmTaskReceiver - TaskExecutor already running
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: RetryPolicy - retry #1 for com.android.voicemail.impl.ActivationTask#d3f6d93 queued, executing in 5000
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask#d3f6d93 added
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - minimal wait time:5000
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - sleep for 5000 millis
2022-01-05 01:50:58.350 4111-8109/? E/GCM: Missing checkin config file
2022-01-05 01:50:58.350 4111-8109/? W/GCM: GCM FAILED TO INITIALIZE - missing checkin
2022-01-05 01:50:58.609 1768-5915/? E/GnssHAL_GnssInterface:
L_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2022-01-05 01:51:00.984 7623-7658/? I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask#d3f6d93
2022-01-05 01:51:00.984 7623-7658/? I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, ***, UserHandle{0} already migrated
2022-01-05 01:51:01.021 7671-7685/? I/VoicemailNotifier: receivers for android.intent.action.PROVIDER_CHANGED :[]
2022-01-05 01:51:01.024 7623-7658/? I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
2022-01-05 01:51:01.025 7623-7658/? I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
2022-01-05 01:51:01.040 7671-7687/? I/VoicemailNotifier: receivers for android.intent.action.PROVIDER_CHANGED :[]
2022-01-05 01:51:01.047 3894-4110/? I/LocationAccessPolicy: Allowing com.android.dialer fine because it doesn't target API 29 yet. Please fix this app. Called from getServiceStateForSubscriber
2022-01-05 01:51:01.050 3894-4110/? I/LocationAccessPolicy: Allowing com.android.dialer coarse because it doesn't target API 29 yet. Please fix this app. Called from getServiceStateForSubscriber
Sorry because I can't comment, you should rebuild app, then open logcat and select error flag to view error log (default is verbose)
With only codes above, we can't help anything
I want the first LoginActivity.java page to open in my project, but AnasayfaActivity.java opens. I couldn't solve the problem. I use Android Studio. I am learning Android, and I would be glad if you help. I shared LoginActivity and AndroidManifest pages. When the application is opened for the first time, the Home Activity opens, when I go back, it goes to the LoginActivity.java page.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geziproject">
>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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/Theme.Geziproject">
<activity android:name=".AnasayfaActivity"/>
<activity android:name=".MainActivity2" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/Theme.Geziproject.NoActionBar">
</activity>
<activity android:name=".bos" />
<activity android:name=".kayitol" />
<activity android:name=".kullanicigiris" />
</application>
</manifest>
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private Button signInButton;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private Button signout;
Button btngiris;
Button btnkayit;
private EditText txtad;
private EditText txtemail;
private EditText txtsifre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button btngiris = findViewById(R.id.btngiris);
Button btnkayit = findViewById(R.id.btnkayit);
txtemail = findViewById(R.id.txtemail);
txtsifre = findViewById(R.id.txtsifre);
signInButton = findViewById(R.id.signin);
mAuth = FirebaseAuth.getInstance();
// signout = findViewById(R.id.sign_out);
btngiris.setOnClickListener(v -> {
String email=txtemail.getText().toString();
String pwd= txtsifre.getText().toString();
if(email.isEmpty()){
txtemail.setError("Lütfen email giriniz");
txtemail.requestFocus();
}
else if(pwd.isEmpty()){
txtsifre.setError("Lütfen şifre giriniz");
txtsifre.requestFocus();
}
else if(email.isEmpty() && pwd.isEmpty())
{
Toast.makeText(LoginActivity.this,"Bu alanlar boş bırakılamaz",Toast.LENGTH_LONG).show();
}
else if(!(email.isEmpty() && pwd.isEmpty())){
mAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, task -> {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Giriş başarısız ,tekrar deneyiniz",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Giriş başarılı",Toast.LENGTH_LONG).show();
txtemail.setText("");
txtsifre.setText("");
startActivity(new Intent(LoginActivity.this,AnasayfaActivity.class));
}
});
}
else{
Toast.makeText(LoginActivity.this,"Hata oluştu",Toast.LENGTH_LONG).show();
}
});
btnkayit.setOnClickListener(v -> {
Intent i= new Intent(LoginActivity.this,kayitol.class);
startActivity(i);
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("1088981466528-8pkjha8350r2uniqg2425nv5itvgpvr7.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(v -> signIn());
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 100);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
//handleSignInResult(task);
if (task.isSuccessful()) {
String s = "Google sign in Successful";
displayToast(s);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
Toast.makeText(getApplicationContext(), "giriş başarılı", Toast.LENGTH_LONG).show();
if (account != null) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(getApplicationContext(), AnasayfaActivity.class);
startActivity(intent);
}
}
});
}
} catch (ApiException e) {
e.printStackTrace();
}
}
}
}
private void displayToast(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
As you set the launch activity in mainfest to LoginActivity, the app starts normally with the LoginActivity, but before the LoginActivity is resumend (i.e. shown on the screen) you added a condition in onCreate() method to launch the AnasayfaActivity as below:
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
If the user is not null (i.e. already logged-in), then the app goes directly to AnasayfaActivity activity without showing the LoginActivity to the user.
And the reason when you go back; the app go to the LoginActivity, because the LoginActivity is still in the back stack. If you want to remove the LoginActivity from the back stack then add Intent.FLAG_ACTIVITY_CLEAR_TOP to the intent:
startActivity(new Intent(LoginActivity.this, AnasayfaActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
I have implemented an app and I have used facebook login to it. Application is running without crashing but facebook login is not working. When I open up the app and click the facebook login button it will show a progress bar and it will be disappeared immediately without doing anything. I have got the following error in the logcat.
2019-08-29 12:45:24.290 19304-19328/com.appic.testfbauth
E/GraphResponse:
{
HttpStatus: 400,
errorCode: 100,
subErrorCode: 33,
errorType: GraphMethodException,
errorMessage: Unsupported get request. Object with ID '742177629556035' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
}
refer below for work I have done.
public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = findViewById(R.id.login_button);
circleImageView = findViewById(R.id.profile_pic);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
checkLoginStatus();
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null) {
txtEmail.setText("");
txtName.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this, "User Logged Out!", Toast.LENGTH_SHORT).show();
}
else loadUser(currentAccessToken);
}
};
private void loadUser(AccessToken newAccessToken) {
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+ id +"/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+ last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(MainActivity.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus() {
if(AccessToken.getCurrentAccessToken() != null) {
loadUser(AccessToken.getCurrentAccessToken());
}
}
}
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ApplicationName"
android:value="#string/app_name"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
I just want to integrate the facebook login and get email, name, image url, id.
I have no enough replication for comment so i paste answer. You just give me answers to my below questions.
You test your app in real device or emulator.?
Get the permission for image?
Please check your browser any facebook account already login there?
If you not getting email and name please try below code:
JSONObject res;
res = new JSONObject(json_object.toString());
String id = res.getString("id");
String name = res.getString("name");
String email = res.getString("email");
Update:
Please Uninstalled FB app from your device and try to login with FB in your app it's working fine.
Update 25/11/209
Also please update your hash key - Please follow this answer
After that convert hash key into base 64 - tomeko.net
I am creating an app just like WhatsApp but I have a problem. The app is suppose to go into the LoginActivity but instead it goes straight into the MainActivity without me logging in.
I tried changing the launcher scene in android manifest and the same thing is happening. I tried adding mAuth.signOut(); at the end of both of my loadingBar.dismiss();. I tried changing this
SendUserToMainActivity(); to this SendUserToRegisterActivity();. I deleted all of the accounts in the firebase database also.
LoginActivity:
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private Button LoginButton, PhoneLoginButton;
private EditText UserEmail, UserPassword;
private TextView NeedNewAccountLink, ForgetPasswordLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
InitializeFields();
NeedNewAccountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllowUserToLogin();
}
});
}
private void AllowUserToLogin() {
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Logging In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields() {
LoginButton = (Button) findViewById(R.id.login_button);
PhoneLoginButton = (Button) findViewById(R.id.phone_login_button);
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
ForgetPasswordLink = (TextView) findViewById(R.id.forget_password_link);
loadingBar = new ProgressDialog(this);
}
#Override
protected void onStart() {
super.onStart();
if (currentUser != null){
SendUserToMainActivity();
}
}
private void SendUserToMainActivity() {
Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(loginIntent);
}
private void SendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
AndroidManifest:
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"/>
</application>
Clear the cache of your app once, change launcher from Main Activity to Login Activity Rebuild the app, and onStart of the LoginActivity you're getting the user logged in that's why he's always sending you to mainActivity,
It doesn't matter if you have removed all users in firebase you'll get auth until you'll clear the cache. Try this solution and let me know if it works for you.
In AllowUserToLogin() you must place a
return;
statement after you show the Toast with the error message.
Also remove the else after checking the password:
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
return;
}
loadingBar.setTitle("Logging In");
..................................
Edit
After you posted the manifest, I see that your LAUNCHER activity is MainActivity although you mention in your question that:
I tried changing the launcher scene in android manifest and the same
thing is happening.
You must also change the LAUNCHER activity to LoginActivity
Change your manifest like this.
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"/>
When opens login activity, check if user already logged send him into MainAcitivty.
Also that will be good if you will have a method, where you will check text fields verification.
Something like this:
public boolean verified() {
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
return false;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter your password",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
And do like this:
if(verified){
loadingBar.setTitle("Logging In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
//And so on.
}
I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>