Gradle sync : No error
Rebuild Project : No error
After hitting RUN >> Installing app through ADB
but unable to launch application. Forced stopped
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.bookcircuit"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
useLibrary 'org.apache.http.legacy'
manifestPlaceholders = [onesignal_app_id : "5c3d7b9b-1874-463f-8081-1c3439ccb3ea",
onesignal_google_project_number: "REMOTE"]
multiDexEnabled true
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Logcat:
2019-05-26 01:29:47.773 29431-29431/com.example.bookcircuit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bookcircuit, PID: 29431
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bookcircuit/com.example.bookcircuit.SplashActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2928)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.constraintlayout.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.bookcircuit-UeVp2v3GMHxcnEsLL2108Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.bookcircuit-UeVp2v3GMHxcnEsLL2108Q==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:606)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:431)
at android.app.Activity.setContentView(Activity.java:2771)
at com.example.bookcircuit.SplashActivity.onCreate(SplashActivity.java:25)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
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.example.bookcircuit">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
tools:node="replace"
android:name=".init.CustomApplication"
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/logo"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="AA_DB_NAME"
android:value="MyDatabase.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="5" />
<meta-data
android:name="AA_MODELS"
android:value="com.example.bookcircuit.db.Notification" />
<!--
Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
if you are calling startActivity above.
-->
<meta-data
android:name="com.onesignal.NotificationOpened.DEFAULT"
android:value="DISABLE" />
<activity android:name=".SplashActivity"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".MainActivity"
android:theme="#style/WhiteTheme" />
<activity
android:name=".LoginActivity"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".HelpCenter"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Profile"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Cart"
android:theme="#style/WhiteTheme" />
<activity
android:name=".UpdateData"
android:theme="#style/WhiteTheme"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ForgotPassword"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".NotificationActivity"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Cards"
android:theme="#style/WhiteTheme" />
<activity
android:name=".IndividualProduct"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Wishlist"
android:theme="#style/WhiteTheme" />
<activity
android:name=".OrderDetails"
android:theme="#style/WhiteTheme" />
<activity
android:name=".OrderPlaced"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Tshirts"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Bags"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Calendars"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Keychains"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Stationary"
android:theme="#style/WhiteTheme" />
<activity android:name=".WelcomeActivity"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
MainActivity :
public class MainActivity extends AppCompatActivity {
private SliderLayout sliderShow;
private Drawer result;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
//to get user session data
private UserSession session;
private HashMap<String, String> user;
private String name, email, photo, mobile;
private String first_time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface typeface = ResourcesCompat.getFont(this, R.font.blacklist);
TextView appname = findViewById(R.id.appname);
appname.setTypeface(typeface);
//check Internet Connection
new CheckInternetConnection(this).checkConnection();
//retrieve session values and display on listviews
getValues();
//Navigation Drawer with toolbar
inflateNavDrawer();
//ImageSLider
inflateImageSlider();
if (session.getFirstTime()) {
//tap target view
tapview();
session.setFirstTime(false);
}
}
private void tapview() {
new TapTargetSequence(this)
.targets(
TapTarget.forView(findViewById(R.id.notifintro), "Notifications", "Latest offers will be available here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true) // Whether to draw a drop shadow or not
.cancelable(false) // Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.first),
TapTarget.forView(findViewById(R.id.view_profile), "Profile", "You can view and edit your profile here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true) // Whether to draw a drop shadow or not
.cancelable(false) // Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.third),
TapTarget.forView(findViewById(R.id.cart), "Your Cart", "Here is Shortcut to your cart !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true)
.cancelable(false)// Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.second),
TapTarget.forView(findViewById(R.id.visitingcards), "Categories", "Product Categories have been listed here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true)
.cancelable(false)// Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.fourth))
.listener(new TapTargetSequence.Listener() {
// This listener will tell us when interesting(tm) events happen in regards
// to the sequence
#Override
public void onSequenceFinish() {
session.setFirstTime(false);
Toasty.success(MainActivity.this, " You are ready to go !", Toast.LENGTH_SHORT).show();
}
#Override
public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) {
}
#Override
public void onSequenceCanceled(TapTarget lastTarget) {
// Boo
}
}).start();
}
private void getValues() {
//create new session object by passing application context
session = new UserSession(getApplicationContext());
//validating session
session.isLoggedIn();
//get User details if logged in
user = session.getUserDetails();
name = user.get(UserSession.KEY_NAME);
email = user.get(UserSession.KEY_EMAIL);
mobile = user.get(UserSession.KEY_MOBiLE);
photo = user.get(UserSession.KEY_PHOTO);
}
private void inflateImageSlider() {
// Using Image Slider -----------------------------------------------------------------------
sliderShow = findViewById(R.id.slider);
//populating Image slider
ArrayList<String> sliderImages = new ArrayList<>();
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/Business_stationery_home_banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/calendar-diaries-home-banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/calendar-diaries-banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/free-visiting-cards-home-banner.JPG");
for (String s : sliderImages) {
DefaultSliderView sliderView = new DefaultSliderView(this);
sliderView.image(s);
sliderShow.addSlider(sliderView);
}
sliderShow.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
}
private void inflateNavDrawer() {
//set Custom toolbar to activity -----------------------------------------------------------
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the AccountHeader ----------------------------------------------------------------
//Profile Making
IProfile profile = new ProfileDrawerItem()
.withName(name)
.withEmail(email)
.withIcon(photo);
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.gradient_background)
.addProfiles(profile)
.withCompactStyle(true)
.build();
//Adding nav drawer items ------------------------------------------------------------------
PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.home).withIcon(R.drawable.home);
PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.myprofile).withIcon(R.drawable.profile);
PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.wishlist).withIcon(R.drawable.wishlist);
PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName(R.string.cart).withIcon(R.drawable.cart);
PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.logout).withIcon(R.drawable.logout);
SecondaryDrawerItem item7 = new SecondaryDrawerItem().withIdentifier(7).withName("Offers").withIcon(R.drawable.tag);
SecondaryDrawerItem item8 = new SecondaryDrawerItem().withIdentifier(8).withName(R.string.aboutapp).withIcon(R.drawable.credits);
SecondaryDrawerItem item9 = new SecondaryDrawerItem().withIdentifier(9).withName(R.string.feedback).withIcon(R.drawable.feedback);
SecondaryDrawerItem item10 = new SecondaryDrawerItem().withIdentifier(10).withName(R.string.helpcentre).withIcon(R.drawable.helpccenter);
SecondaryDrawerItem item12 = new SecondaryDrawerItem().withIdentifier(12).withName("App Tour").withIcon(R.drawable.tour);
SecondaryDrawerItem item13 = new SecondaryDrawerItem().withIdentifier(13).withName("Explore").withIcon(R.drawable.explore);
//creating navbar and adding to the toolbar ------------------------------------------------
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withHasStableIds(true)
.withDrawerLayout(R.layout.crossfade_drawer)
.withAccountHeader(headerResult)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withTranslucentStatusBar(true)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
item1, item2, item3, item4, item5, new DividerDrawerItem(), item7, item8, item9, item10,new DividerDrawerItem(),item12,item13
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch (position) {
case 1:
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
}
break;
case 2:
startActivity(new Intent(MainActivity.this, Profile.class));
break;
case 3:
startActivity(new Intent(MainActivity.this, Wishlist.class));
break;
case 4:
startActivity(new Intent(MainActivity.this, Cart.class));
break;
case 5:
session.logoutUser();
finish();
break;
case 7:
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
break;
case 8:
new LibsBuilder()
.withFields(R.string.class.getFields())
.withActivityTitle(getString(R.string.about_activity_title))
.withAboutIconShown(true)
.withAboutAppName(getString(R.string.app_name))
.withAboutVersionShown(true)
.withLicenseShown(true)
.withAboutSpecial1(getString(R.string.domain))
.withAboutSpecial1Description(getString(R.string.website))
.withAboutSpecial2(getString(R.string.licence))
.withAboutSpecial2Description(getString(R.string.licencedesc))
.withAboutSpecial3(getString(R.string.changelog))
.withAboutSpecial3Description(getString(R.string.changes))
.withShowLoadingProgress(true)
.withAboutDescription(getString(R.string.about_activity_description))
.withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
.start(MainActivity.this);
break;
case 9:
new EasyFeedback.Builder(MainActivity.this)
.withEmail("beingdevofficial#gmail.com")
.withSystemInfo()
.build()
.start();
break;
case 10:
startActivity(new Intent(MainActivity.this, HelpCenter.class));
break;
case 12:
session.setFirstTimeLaunch(true);
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish();
break;
case 13:
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
}
tapview();
break;
default:
Toast.makeText(MainActivity.this, "Default", Toast.LENGTH_LONG).show();
}
return true;
}
})
.build();
//Setting crossfader drawer------------------------------------------------------------
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
final MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
}
#Override
protected void onStop() {
sliderShow.stopAutoCycle();
super.onStop();
}
#Override
public void onBackPressed() {
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
public void viewProfile(View view) {
startActivity(new Intent(MainActivity.this, Profile.class));
}
public void viewCart(View view) {
startActivity(new Intent(MainActivity.this, Cart.class));
}
#Override
protected void onResume() {
//check Internet Connection
new CheckInternetConnection(this).checkConnection();
sliderShow.startAutoCycle();
super.onResume();
}
public void Notifications(View view) {
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
}
public void cardsActivity(View view) {
startActivity(new Intent(MainActivity.this, Cards.class));
}
public void tshirtActivity(View view) {
startActivity(new Intent(MainActivity.this, Tshirts.class));
}
public void bagsActivity(View view) {
startActivity(new Intent(MainActivity.this, Bags.class));
}
public void stationaryAcitivity(View view) {
startActivity(new Intent(MainActivity.this, Stationary.class));
}
public void calendarsActivity(View view) {
startActivity(new Intent(MainActivity.this, Calendars.class));
}
public void keychainsActivity(View view) {
startActivity(new Intent(MainActivity.this, Keychains.class));
}
}
Just add in your app(the one which says Module:app) level build.gradle
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
in you log data, we can clearly see
"Caused by: android.view.InflateException: Binary XML file line #2: Binary
XML file line #2: Error inflating class
androidx.constraintlayout.ConstraintLayout"
after implementing the constraint-layout library, just sync and clean your project.
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));
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
I'm trying to send content through Intent (I think this is the reason of my error) and I constantly get ActivityNotFoundException.
Here's the class which is sending data to Tab1.class (String called temperature)
I found similar question on stack where someone wrote that problem is caused by instantiating the intent before the activity has gone through its life cycle methods but I'm not sure if it is a problem and what should I do to fix it
public class ChooseLayout extends AppCompatActivity implements View.OnClickListener {
EditText editText;
Button button;
Weather weather;
Parser parser = new Parser();
SharedPreferences sharedPreferences;
String temperature, preassure,WindSpeed,WindDirection,Humidity,ViewDescription;
boolean isChecked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_layout);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isOnline()) {
Toast.makeText(getApplicationContext(), "Cannot connect to network, data will be restore from file with last downloaded data...", Toast.LENGTH_LONG).show();
} else {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
weather = parser.getWeatherForLocation(editText.getText() + "");
runOnUiThread(new Runnable() {
#Override
public void run() {
editText.setText(weather.getCity() + ", " + weather.getCountry());
temperature = weather.getTemperature();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
Intent intent = new Intent(getApplicationContext(),Tab1.class);
intent.putExtra("temperature", temperature);
startActivity(intent);
}
});
sharedPreferences = getSharedPreferences("file_name", MODE_PRIVATE);
}
I have declared this activity in AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chirag.slidingtabsusingviewpager">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
<activity android:name=".ChooseLayout"></activity>
</application>
</manifest>
You can either add or replace fragment in your activity.
Then do this in your activity to add fragment:
FragmentManager manager = getSupportFragmentManager();
Tab1 tab1 = new Tab1();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(android.R.id.content, tab1);
transaction.commit();
Or to replace fragment do this:
FragmentManager manager = getSupportFragmentManager();
Tab1 tab1 = new Tab1();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(android.R.id.content, tab1);
transaction.commit();
To pass data from fragment you can use Bundle as,
Bundle bundle = new Bundle();
bundle.putString("your_tag", your_string);
FragmentManager manager = getSupportFragmentManager();
Tab1 tab1 = new Tab1();
tab1.setArguments(bundle);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(android.R.id.content, tab1);
transaction.commit();
To know about more fragment-transaction check this https://developer.android.com/reference/android/app/FragmentTransaction.html
I am building a voice recognition app that does something when I say a specific word such as "open" and it opens something etc. but the problem is that my app keep crashing when I run it on my phone (real device) and I tap the speak button. I don't know what else to do? I tried giving it internet and voice recognition permission but it still doesn't help
here is the code in java (android studio)
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.SpeakButton);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
startVoiceRecognitionActivity();
}
});
}
void startVoiceRecognitionActivity(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult (int requestCode,int resultCode, Intent data){
String wordStr = null;
String[] words = null;
String firstWord = null;
String secondWord = null;
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK)
{
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
wordStr = matches.get(0);
words = wordStr.split(" ");
firstWord = words[0];
secondWord = words[1];
}
if (firstWord.equals("open"))
{
resultText = (TextView)findViewById(R.id.ResultText);
resultText.setText("Results: Open Command Works");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starlinginteractivesoftworks.musiccompanion">
<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">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I look at the log and it said:
08-07 20:12:57.813 14350-14350/? E/BoostFramework: BoostFramework() :
Exception_1 = java.lang.ClassNotFoundException: Didn't find class
"com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib64,
/vendor/lib64]] 08-07 20:12:58.509
14350-14350/com.starlinginteractivesoftworks.musiccompanion
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.starlinginteractivesoftworks.musiccompanion, PID: 14350
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.speech.action.RECOGNIZE_SPEECH
launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } (has
extras) }
at
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1839)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1531)
at android.app.Activity.startActivityForResult(Activity.java:4399)
at android.app.Activity.startActivityForResult(Activity.java:4358)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity.startVoiceRecognitionActivity(MainActivity.java:55)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity$1.onClick(MainActivity.java:43)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
The boost framework log is just a warning, no worry about it. The real problem is the
ActivityNotFoundException: No Activity found to handle Intent
It can come from:
a poor connectivity
the voice app is missing on your phone
Possible solutions
Ensure you have a recognition app installed (see ActivityNotFoundException: No Activity found to handle Intent (RECOGNIZE_SPEECH) for more details).
Try to enable offline mode as explained here:
On your device go to Settings -> Language and Input. Click on icon on Google voice input.
Under ALL tab select the language you want to download.
Once the language package downloaded, you can see it under INSTALLED tab.
Workarounds
Catch the exception and open a webview to download a recognition app:
try{
...
}
catch(ActivityNotFoundException e) {
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://market.android.com/details?id=APP_PACKAGE_NAME"));
startActivity(i);
}
Check that a recognition app is available before the startActivity (see https://stackoverflow.com/a/35290037/2667536):
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
//Then there is application can handle your intent
}else{
//No Application can handle your intent
}