In my new game I want to show interstitial ads. With a button click the game restarts and I want the ads to show up only every 15th time. The problem is that it is shown every time the game starts. Where is the fault?
public class MainActivity extends AppCompatActivity {
InterstitialAd mInterstitialAd;
public int playcount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
AdRequest adRequest = new AdRequest.Builder()
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
TextView playctv = (TextView) findViewById(R.id.textView);
SharedPreferences prefsplay = this.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
playcount = prefsplay.getInt("play_number", 0);
playctv.setText(String.valueOf(playcount));
}
public void restart(View view) {
Intent intent = new Intent(this, GameScreen.class);
startActivity(intent);
playcount++;
SharedPreferences prefsplay = this
.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
prefsplay.edit().putInt("play_number", playcount)
.apply();
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded())
mInterstitialAd.show();
}
private void adView() {
mAdView = (AdView) findViewById(R.id.adView);
MobileAds.initialize(getApplicationContext(), getResources().getString(R.string.interstitial_full_screen));
final AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
public void gameover() {
if (playcount == 10) {
playcount = 0;
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
mInterstitialAd.show(); //We are executing this code only if ad is loaded, no need to check it again
SharedPreferences prefsplay = getApplicationContext()
.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
prefsplay.edit().putInt("play_number", playcount)
.apply();
AdRequest adRequest = new AdRequest.Builder()
.build();
}
});
}
}
}
Activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:id="#+id/rect" >
<ImageView
android:id="#+id/imageview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageview1"
android:layout_alignTop="#+id/imageview1"
android:alpha="0.7"
android:gravity="center"
android:text="Score"
android:textSize="15sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:alpha="0.9"
android:gravity="center"
android:text="sco"
android:textSize="25sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="0:500"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:alpha="0.7"
android:layout_alignTop="#+id/textView2"
android:text="Highscore"
android:textSize="15sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignRight="#+id/textView4"
android:text="Hs"
android:textSize="25sp" />
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
ads:adSize="SMART_BANNER" ads:adUnitId="#string/banner_home_footer"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
</com.google.android.gms.ads.AdView>
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_default"
android:onClick="restart"
android:src="#android:drawable/ic_menu_revert"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_alignLeft="#+id/imageButton1"
android:layout_alignStart="#+id/imageButton1"
android:id="#+id/textView" />
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx"
android:versionCode="2"
android:versionName="1.1" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#drawable/logoone"
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" />
<activity
android:name=".MainActivity"
android:screenOrientation="sensorPortrait"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GameScreen"
android:screenOrientation="sensorPortrait"
android:label="#string/app_name" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Your code needs a lot of fixing. I'm putting one by one here.
The restart function should use startActivityForResult
private final int ACTION_GAME = 100;
public void restart(View view) {
Intent intent = new Intent(this, GameScreen.class);
startActivityForResult(intent, ACTION_GAME);
playcount++;
SharedPreferences prefsplay = this
.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefsplay.edit().putInt("play_number", playcount).apply();
}
As you've started the GameScreen activity for a result, you need to override the onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_GAME:
gameover();
break;
default:
break;
}
}
Now in the gameover function you need to check the saved value in your preference for the playcount.
public void gameover() {
// Get the saved value
SharedPreferences prefsplay = this
.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
playcount = prefsplay.getInt("play_number", 0);
if (playcount >= 10) {
playcount = 0;
showInterstitial();
SharedPreferences prefsplay = getApplicationContext()
.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefsplay.edit().putInt("play_number", playcount).apply();
// Start loading the new ad
loadNewAd();
}
}
I've introduced loadNewAd() function which might look like this
private void loadNewAd() {
final AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
And the onCreate function needs to be modified like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
// Call adView here
adView();
TextView playctv = (TextView) findViewById(R.id.textView);
SharedPreferences prefsplay = this.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
playcount = prefsplay.getInt("play_number", 0);
playctv.setText(String.valueOf(playcount));
}
Finally, as you're using startActivityForResult you need to set the result while finishing your GameScreen activity. So when you finish or return from the GameScreen activity, you need to do this.
GameScreen.setResult(Activity.RESULT_OK);
GameScreen.finish();
Related
I building an simple app when i sign in through Google or Facebook from the LoginActivity the app must start a new activity and store the login data for future so that user won't have to login next time with the same account.
I have have created a custom button for the Facebook and Google login but the Facebook login not working and Once i logged in with the Google account and then i sign out from the MainActivity the Google signout method not working and the again move to MainActivity without asking for login.
I also added a button in Navigation Drawer that should sign out user but the Google account not disconnecting i don't know what is the issue because i am new to android. so please help me.
Here is the LoginActivity.java file
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "LoginActivity";
MaterialTextView txtLogin, txtSignUp;
MaterialButton btnLogin;
FrameLayout fb, google;
ImageView fb_icon, google_icon;
LoginButton facebook_login_button;
SignInButton google_signIn_button;
GoogleSignInClient mGoogleSignInClient;
SharedPreferences newsharedPreferences;
public ConstraintLayout LoginLayout;
public int RC_SIGN_IN = 1001;
public String FBemail, FBfirstname, FBlastname, FBid, FBprofile_pic_url;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtLogin = findViewById(R.id.txtLogin);
txtSignUp = findViewById(R.id.txtSignUp);
fb = findViewById(R.id.fb);
google = findViewById(R.id.g);
fb_icon = findViewById(R.id.fb_icon);
google_icon = findViewById(R.id.google_icon);
facebook_login_button = findViewById(R.id.facebook_login_button);
google_signIn_button = findViewById(R.id.google_signIn_button);
LoginLayout = (ConstraintLayout) findViewById(R.id.LoginLayout);
//Google login
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
newsharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
callbackManager = CallbackManager.Factory.create();
txtLogin.setOnClickListener(this);
txtSignUp.setOnClickListener(this);
facebook_login_button.setOnClickListener(this);
google_signIn_button.setOnClickListener(this);
fb_icon.setOnClickListener(this);
google_icon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.txtSignUp:
txtanimation();
break;
case R.id.fb_icon:
if(v == fb_icon)
{
facebook_login_button.performClick();
}
facebook_login_button.setReadPermissions(Arrays.asList("email", "public_profile"));
facebook_login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
String accessToken = loginResult.getAccessToken().getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
String accessToken = loginResult.getAccessToken().getToken();
Log.i("accessToken", accessToken);
try {
FBfirstname = object.getString("first_name");
FBlastname = object.getString("last_name");
FBemail = object.getString("email");
FBid = object.getString("id");
FBprofile_pic_url = "https://graph.facebook.com/" + FBid + "/picture?type=normal";
SharedPreferences.Editor editor = newsharedPreferences.edit();
editor.putString("ProfileName", FBfirstname + FBlastname);
editor.putString("ProfileEmail", FBemail);
editor.putString("ProfilePhoto", FBprofile_pic_url);
editor.apply();
editor.commit();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Log.i("OnCompelete", FBfirstname);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameteres = new Bundle();
parameteres.putString("Fields", "id, first_name, last_name, public_profile, email");
request.setParameters(parameteres);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
break;
case R.id.google_icon:
if(v == google_icon)
{
google_signIn_button.performClick();
}
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
break;
case R.id.btnLogin:
break;
}
}
//Check for the last signed in account when activity starts.
#Override
protected void onStart () {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
Log.i("googleAccount", String.valueOf(account));
updateUI(account);
}
//for sign out from google.
public void googleSignOUT () {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
}
// for disconnect the google account from the app.
public void revokeAccess() {
mGoogleSignInClient.revokeAccess()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
}
// App ui will change upon the if the user logged in or not
private void updateUI (GoogleSignInAccount account){
if (account != null) {
Toast.makeText(this, "User already logged in ", LENGTH_LONG).show();
String ACName = account.getDisplayName();
String personEmail = account.getEmail();
Uri personPhoto = account.getPhotoUrl();
Log.i("gphoto", String.valueOf(personPhoto));
SharedPreferences.Editor editor = newsharedPreferences.edit();
editor.putString("ProfileName", ACName);
editor.putString("ProfileEmail", personEmail);
editor.putString("ProfilePhoto", String.valueOf(personPhoto));
editor.apply();
editor.commit();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
else
{
Toast.makeText(this, "User not logged in Please log in first", LENGTH_LONG).show();
revokeAccess();
}
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, #Nullable Intent data){
//facebook login
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
//Google Sign in
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult (Task < GoogleSignInAccount > task) {
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
updateUI(account);
} catch (ApiException e) {
e.printStackTrace();
new MaterialAlertDialogBuilder(this).setTitle("Sign In Error")
.setMessage(e.getStatusCode() + "\n" + GoogleSignInStatusCodes.getStatusCodeString(e.getStatusCode()))
.setPositiveButton("Retry", null)
.show();
Log.i("FailedCode", "SignInResulte- Failed Code" + e.getStatusCode());
Log.i("StatusMessage", "SignInFailed--Reason" + e.getStatusMessage());
}
}
private void txtanimation () {
Animation animation = AnimationUtils.loadAnimation(this, R.anim.txtanimation);
txtSignUp.setTextSize(36);
txtSignUp.setTextColor(Color.parseColor("#FFFCFF"));
//to change the margin
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) txtSignUp.getLayoutParams();
params.setMargins(100, 15, 0, 0);
txtSignUp.setLayoutParams(params);
txtSignUp.startAnimation(animation);
txtLogin.setTextSize(26);
txtLogin.setTextColor(Color.parseColor("#645853"));
ConstraintLayout.LayoutParams secondparams = (ConstraintLayout.LayoutParams) txtLogin.getLayoutParams();
params.setMargins(200, 5, 0, 0);
txtLogin.setLayoutParams(secondparams);
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
}
Here is the login_activity.XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity"
android:background="#color/mattBlackone"
android:id="#+id/LoginLayout">
<com.google.android.material.textview.MaterialTextView
android:id="#+id/txtLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="Login"
app:textAllCaps="false"
android:textColor="#color/Snow"
android:textSize="35sp"
android:fontFamily="#font/roboto_regular"
android:layout_marginTop="10dp"
android:layout_marginRight="200dp"
android:elevation="10dp"
android:shadowColor="#color/SnowShadow"
android:clickable="true"/>
<com.google.android.material.textview.MaterialTextView
android:id="#+id/txtSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="#+id/txtLogin"
android:text="Sign Up"
android:textSize="26sp"
app:textAllCaps="false"
android:textColor="#color/Umber"
android:layout_marginTop="20dp"
android:layout_marginLeft="100dp"
android:fontFamily="#font/roboto_regular"
android:elevation="10dp"
android:shadowColor="#color/SnowShadow"
android:clickable="true"/>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/loginId"
android:layout_width="300dp"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:boxStrokeColor="#color/Nblue"
android:layout_marginTop="200dp"
app:boxStrokeWidth="2dp"
android:elevation="10dp"
app:hintTextColor="#color/Nblue">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:hint="Email ID"
android:imeOptions="actionNext"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/loginPassword"
android:layout_width="300dp"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:boxStrokeColor="#color/Nblue"
android:layout_marginTop="300dp"
app:boxStrokeWidth="2dp"
app:endIconMode="password_toggle"
app:hintTextColor="#color/Nblue"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:hint="Password"
android:imeOptions="actionNext"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textview.MaterialTextView
android:id="#+id/txtForgatPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forgate Password ?"
android:textSize="16sp"
android:textColor="#color/Umber"
app:textAllCaps="false"
android:fontFamily="#font/roboto_regular"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/btnLogin"
app:layout_constraintTop_toBottomOf="#id/loginPassword"
android:layout_marginLeft="155dp"
android:layout_marginBottom="10dp"
android:clickable="true"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/btnLogin"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="250dp"
android:layout_height="50dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/loginPassword"
app:strokeColor="#color/Nblue"
app:strokeWidth="1dp"
android:text="Login"
android:textSize="22sp"
android:textColor="#color/Snow"
android:elevation="10dp"
app:cornerRadius="12dp"
android:fontFamily="#font/roboto_light"
android:textAllCaps="false"
android:layout_marginTop="60dp"
app:rippleColor="#color/Nblue"
android:shadowColor="#color/SnowShadow"/>
<FrameLayout
android:id="#+id/fb"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginRight="200dp"
android:layout_marginBottom="100dp">
<com.facebook.login.widget.LoginButton
android:id="#+id/facebook_login_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="40dp"
android:visibility="gone"/>
<ImageView
android:id="#+id/fb_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/facebook_icon"
android:layout_gravity="center"
android:clickable="true"/>
</FrameLayout>
<FrameLayout
android:id="#+id/g"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginBottom="100dp"
android:layout_marginStart="200dp"
android:clickable="true">
<com.google.android.gms.common.SignInButton
android:id="#+id/google_signIn_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
android:layout_marginBottom="60dp"/>
<ImageView
android:id="#+id/google_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/google_icon"
android:layout_gravity="center"
android:clickable="true"/>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the MainActivity.java file in which i am performing signout process
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
DrawerLayout drawerLayout;
TextView upperText, LowerText;
ImageView profile_imageView;
SharedPreferences mysharedPreferences;
MaterialButton btn_sign_out;
String Name, Email, Photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
//To set the porfile information in the header of the navigation drawer
mysharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);
View header = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
btn_sign_out = findViewById(R.id.btn_log_out);
upperText = header.findViewById(R.id.upperText);
LowerText = header.findViewById(R.id.LowerText);
profile_imageView = header.findViewById(R.id.profile_imageView);
Name = mysharedPreferences.getString("ProfileName", Name);
Email = mysharedPreferences.getString("ProfileEmail", Email);
Photo = mysharedPreferences.getString("ProfilePhoto", Photo);
Log.i("profile" ,Name);
Log.i("profileEmail" ,Email);
Log.i("profilePhoto" ,Photo);
upperText.setText(Name);
LowerText.setText(Email);
Glide.with(header).load(Photo).into(profile_imageView);
btn_sign_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginActivity loginActivity = new LoginActivity();
loginActivity.googleSignOUT();
loginActivity.revokeAccess();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawerLayout, toolbar, R.string.nav_app_bar_open_drawer_description,
R.string.navigation_drawer_close);
NavigationView navigationView = findViewById(R.id.nav_view);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawerLayout)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId())
{
case R.id.nav_log_out:
break;
}
return true;
}
}
Here is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
style="#style/Widget.Custom.NavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="30dp">
<com.google.android.material.button.MaterialButton
android:id="#+id/btn_log_out"
android:layout_width="250dp"
android:layout_height="50dp"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:text="Sign Out"
android:textColor="#color/Snow"
android:textSize="18sp"
android:textAllCaps="false"
app:strokeColor="#color/Dwhite"
app:strokeWidth="1dp"
app:cornerRadius="12dp"/>
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Here is Manifest.XML file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akapplicationsinc.nillu_hair_saloon">
<uses-permission android:name="android.permission.INTERNET"/>
<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">
<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=".SplashActivity">
</activity>
<activity android:name=".RegisterActivity" />
<activity android:name=".MainActivity" />
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can anyone tell me how to perform both logout (Facebook and Google) with a single item or button in navigation drawer Your knowledge will teach me new things and i will admire your help.
Try sign out using this code
btn_sign_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoogleSignIn.getClient(
getContext(),
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build()
).signOut();
LoginManager.getInstance().logOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class)); }
});
I am new at android and I am trying when someone type a string in search view when click search then this typed string or whatever should in web view at the google search for this.
I have manually gave a string and it is working but I need to implement a search. I have added uses permission for Internet in Manifest
This is my code.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/webView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.22000003">
<EditText
android:id="#+id/search_for"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType=""
android:autofillHints="" />
<Button
android:id="#+id/myButton"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</SearchView>
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="45dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.47000003" />
</android.support.constraint.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edit = (EditText) findViewById(R.id.search_for);
final Button searchBtn = (Button) findViewById(R.id.myButton);
final String searchText = edit.getText().toString();
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.loadUrl("http://www.google.com/search?q=" + searchText);
}
});
}
}
This is my Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zhuniqia.searchwithus">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<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>
</application>
</manifest>
Xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:orientation="horizontal">
<EditText
android:id="#+id/search_for"
android:imeOptions="actionSearch"
android:inputType="text"
android:layout_width="match_parent"
android:layout_toLeftOf="#id/myButton"
android:layout_height="wrap_content"
android:hint="Search" />
<Button
android:id="#+id/myButton"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_width="60dp"
android:text="Go"
/>
</RelativeLayout>
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/></LinearLayout>
Java Class
public class MainActivity extends AppCompatActivity {
public WebView myWeb;
public Button myBtn;
public EditText myEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWeb = findViewById(R.id.webView);
myBtn = findViewById(R.id.myButton);
myEdit = findViewById(R.id.search_for);
myEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
final String myText = myEdit.getText().toString();
myWeb.loadUrl("http://www.google.com/search?q=" + myText);
return true;
}
return false;
}
});
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String myText = myEdit.getText().toString();
myWeb.loadUrl("http://www.google.com/search?q=" + myText);
}
});
myWeb.getSettings().setJavaScriptEnabled(true);
myWeb.setWebChromeClient(new WebChromeClient());
myWeb.setWebViewClient(new WebViewClient());
myWeb.loadUrl("https://www.google.com");
}}
i cannot give you a full answer now, but maybe it will useful for you to think towards setText and getText functions
Use EditText and a Button
final EditText edit = (EditText) findViewById(R.id.text_xyz);
final Button searchBtn = (Button) findViewById(R.id.myBuuton);
get text from EditText
String searchtext = edit.getText().toString();
Set Button to search the text you entered
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.loadUrl("http://www.google.com/search?q=" + searchtext);
}
});
I have been trying to implement splash Screen to my app with help of many codes avaible in sites , but none worked for me.
Each time the app is crashing after displaying splash screen for 3 secs.
I don't know where i'm going wrong , please make corrections to my code to display splash screen correctly ! Thank You !
//This is my Main activity
1. public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button) this.findViewById(R.id.gg);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.gg);
one.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Good Game", Toast.LENGTH_SHORT).show();
mp1.start();
}
});
Button two = (Button) this.findViewById(R.id.gm);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.gm);
two.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Oh, They got me!", Toast.LENGTH_SHORT).show();
mp2.start();
}
});
Button three = (Button) this.findViewById(R.id.cb);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.cb);
three.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Come on boy", Toast.LENGTH_SHORT).show();
mp3.start();
}
});
Button four = (Button) this.findViewById(R.id.ns);
final MediaPlayer mp4 = MediaPlayer.create(this, R.raw.ns);
four.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Nice shot", Toast.LENGTH_SHORT).show();
mp4.start();
}
});
Button five = (Button) this.findViewById(R.id.wp);
final MediaPlayer mp5 = MediaPlayer.create(this, R.raw.wp);
five.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You wanna piece of me!", Toast.LENGTH_SHORT).show();
mp5.start();
}
});
Button six = (Button) this.findViewById(R.id.bi);
final MediaPlayer mp6 = MediaPlayer.create(this, R.raw.bi);
six.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Bring it", Toast.LENGTH_SHORT).show();
mp6.start();
}
});
Button seven = (Button) this.findViewById(R.id.lg);
final MediaPlayer mp7 = MediaPlayer.create(this, R.raw.lg);
seven.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Let’s go, Yeah!", Toast.LENGTH_SHORT).show();
mp7.start();
}
});
Button eight = (Button) this.findViewById(R.id.ru);
final MediaPlayer mp8 = MediaPlayer.create(this, R.raw.ru);
eight.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Ready Up", Toast.LENGTH_SHORT).show();
mp8.start();
}
});
Button nine = (Button) this.findViewById(R.id.nn);
final MediaPlayer mp9 = MediaPlayer.create(this, R.raw.nn);
nine.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Nooooo", Toast.LENGTH_SHORT).show();
mp9.start();
}
});
Button ten = (Button) this.findViewById(R.id.cm);
final MediaPlayer mp10 = MediaPlayer.create(this, R.raw.cm);
ten.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Cover me", Toast.LENGTH_SHORT).show();
mp10.start();
}
});
Button eleven = (Button) this.findViewById(R.id.hh);
final MediaPlayer mp11 = MediaPlayer.create(this, R.raw.hh);
eleven.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Hoo-ya", Toast.LENGTH_SHORT).show();
mp11.start();
}
});
Button twelve = (Button) this.findViewById(R.id.mo);
final MediaPlayer mp12 = MediaPlayer.create(this, R.raw.mo);
twelve.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Move out", Toast.LENGTH_SHORT).show();
mp12.start();
}
});
Button thirteen = (Button) this.findViewById(R.id.gs);
final MediaPlayer mp13 = MediaPlayer.create(this, R.raw.gs);
thirteen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Get Some", Toast.LENGTH_SHORT).show();
mp13.start();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Your Messege",Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
//This is my activity_main.xml
2. <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.android.mmm.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
//This is content_main.xml
3. <android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.android.mmm.MainActivity"
tools:showIn="#layout/activity_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000">
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="GG"
android:id="#+id/gg"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/gm"
android:layout_width="100dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:text="GM"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold"
tools:ignore="HardcodedText" />
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="CB"
android:id="#+id/cb"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="NS"
android:id="#+id/ns"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="WP"
android:id="#+id/wp"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="BI"
android:id="#+id/bi"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="LG"
android:id="#+id/lg"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="RU"
android:id="#+id/ru"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="NN"
android:id="#+id/nn"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="CM"
android:id="#+id/cm"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="HH"
android:id="#+id/hh"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="MO"
android:id="#+id/mo"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="100dp"
android:layout_height="48dp"
android:text="GS"
android:id="#+id/gs"
android:textSize="18sp"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#000000"
tools:ignore="HardcodedText"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
//This is AndroidManifest.xml
4. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.mmm">
<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=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
//This is styles.xml
5. <resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
//This is my SplashActivity.Java
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
6. //This is activity_splash.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/wwe_logo" />
</RelativeLayout>
AppCompatActivity has it's own toolbar so you need to remove it by using android:theme="#style/AppTheme.NoActionBar" in manifest
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
</activity>
Although if you are not doing much customization in your toolbar then your can also skip creating your own toolbar by removing it from XML and removing it's initialization from java code as well but by doing this , you will lose the feature of collapsing toolbar
Making a splash screen is actually pretty easy.
1. Create drawable
In my case, I created a drawable named splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:opacity="opaque">
<item android:drawable="#color/colorWhite" />
<item>
<bitmap
android:gravity="center"
android:src="#drawable/sensesmart_icon" />
</item>
2. Add drawable to your styles.xml
Here I just added my drawable to styles:
<style name="SplashTheme" parent="AppTheme">
<item name="android:windowBackground">#drawable/splash</item>
</style>
3. Add splash to manifest
You want to actually tell your app that the splash layout should show before the app has loaded:
<activity android:name=".BaseActivity"
android:screenOrientation="portrait"
android:theme="#style/SplashTheme"> <!--Splash screen-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
4. Set theme on your starting activity
In my case, BaseActivity is the activity which starts my application, so inside my onCreate(), I start with setting my theme:
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_base);
super.onCreate(savedInstanceState);
}
This is the only thing you need to do. If you use this method, the splash screen doesn't stay for longer than it needs. Your contentView will start as soon as you have loaded your app.
Hope this helps!
I have made a app which uses phones SMS sending, reading permission. It sends a message on button click and displays incoming message from a particular number.
It is working fine with Android 5 and older versions of android but is not working with Android 6. When android 6 users are pressing the button, app is crashing. I am sharing my code below, please help me fix this error.
Main_Activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tti.traceanyvehiclewithdetails.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:src="#drawable/ffff"
android:alpha="0.4"
android:scaleType="fitCenter"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btnSendSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/send_sms"
android:minHeight="60dp"
android:background="#f4843e"
android:textColor="#000000"
android:textSize="33dp"
android:layout_gravity="center"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:layout_alignRight="#+id/imageView"
android:layout_alignEnd="#+id/imageView" />
<EditText
android:id="#+id/enterDetail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:lines="1"
android:gravity="top"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="74dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter Vehicle Number:"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false"
android:contextClickable="false"
android:textSize="35dp"
android:paddingTop="4dp"
android:paddingLeft="3dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/enterDetail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:longClickable="true"
android:textSize="25dp"
android:typeface="sans"
android:contextClickable="true"
android:clickable="true"
android:textColor="#0066ff"
android:layout_marginTop="5dp"
android:paddingLeft="5dp"
android:paddingTop="2dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:textStyle="bold"
android:textIsSelectable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Example: DL 15Y 2597"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="47dp"
android:paddingLeft="6dp" />
<!-- view for AdMob Banner Ad -->
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:progressDrawable="#drawable/circular_progress_bar"
android:layout_below="#+id/textView1"
android:layout_above="#+id/btnSendSMS"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:layout_alignLeft="#+id/adView"
android:layout_alignStart="#+id/adView"
android:padding="60dp"
android:layout_marginTop="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView3"
android:layout_alignTop="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#ee2467"
android:textSize="25dp" />
</RelativeLayout>
Mainactivity.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class MainActivity extends AppCompatActivity {
InterstitialAd mInterstitialAd;
Button btnSendSMS;
EditText enteredNum;
IntentFilter intentFilter;
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//---display the SMS received in the TextView---
TextView loadingMsg = (TextView) findViewById(R.id.textView3);
loadingMsg.setText("");
spinner.setVisibility(View.GONE);
TextView SMSes = (TextView) findViewById(R.id.textView1);
SMSes.setText(intent.getExtras().getString("sms"));
}
};
public ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView loadingMsg = (TextView) findViewById(R.id.textView3);
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
btnSendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enteredNum = (EditText) findViewById(R.id.enterDetail);
assert enteredNum != null;
sendSMS("+917738299899", "VAHAN " + enteredNum.getText().toString().replaceAll(" ", "").toUpperCase());
Toast.makeText(getApplicationContext(), "Please wait while Loading Vehicle Details", Toast.LENGTH_LONG).show();
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
spinner.setVisibility(View.VISIBLE);
loadingMsg.setText("Please wait while vehicle details are loading, it usually takes less than 30 seconds.");
TextView SMSes = (TextView) findViewById(R.id.textView1);
SMSes.setText("");
}
});
// Load an ad into the AdMob banner view.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
#Override
protected void onResume() {
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
//---unregister the receiver---
unregisterReceiver(intentReceiver);
super.onPause();
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
SMSReceiver.java:
package tti.traceanyvehiclewithdetails;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SMSReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
int c=0;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if(msgs[i].getOriginatingAddress().indexOf("VAAHAN")!= -1) {
c=1;
str += msgs[i].getMessageBody().toString();
str += "\n";
}
}
if(c==1) {
//---send a broadcast intent to update the SMS received in the activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tti.traceanyvehiclewithdetails">
<!-- Include required permissions for Google Mobile Ads to run. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- This meta-data tag is required to use Google Play Services. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Include the AdActivity configChanges and theme. -->
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
for Android 6.0 and above you need to request permissions at runtime.
please refer this :
https://developer.android.com/training/permissions/requesting.html
You may use a 3rd party library as well.
look here :
https://android-arsenal.com/tag/235
I have two Activities MainActivity and Register when i intent from MainActivity to Register the button listener in Register class is not working.
Here is the code
MainActivity
public class MainActivity extends AppCompatActivity {
// defining all the components
AlertDialog builder;
public EditText Email,Password;
public ImageButton fb,twitter;
public Button register;
public String email;
public String password;
public BackgroungWorker backgroungWorker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
builder = new AlertDialog.Builder(this).create();
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
Email= (EditText) findViewById(R.id.email);
Password= (EditText) findViewById(R.id.pass);
fb= (ImageButton) findViewById(R.id.fb_button);
twitter= (ImageButton) findViewById(R.id.tw_button);
register = (Button) findViewById(R.id.register);
}
// for listening to the events
public void eventHappend(View view)
{
if(view.getId()==R.id.login)
{
email = Email.getText().toString();
password = Password.getText().toString();
if(email.equals(""))
{
showMessage("Error","Email cannot be blank");
return;
}
if(password.equals(""))
{
showMessage("Error","Enter your password");
return;
}
backgroungWorker = new BackgroungWorker(this);
backgroungWorker.execute("Login",email,password);
}
if(view.getId()==R.id.register)
{
// INTENT TO REGISTER ACTIVITY
Intent intent = new Intent(MainActivity.this,Register.class);
startActivity(intent);
}
if(view.getId()==R.id.forgot)
{
}
if(view.getId()== R.id.fb_button)
{
showToast("Facebook!!");
}
if(view.getId()==R.id.tw_button)
{
showToast("Twitter");
}
}
public void showToast(String s)
{
Toast toast = new Toast(this);
toast.makeText(this,s, Toast.LENGTH_SHORT).show();
}
public void showMessage(String title,String message)
{
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
builder.show();
}}
Register
public class Register extends Activity {
String user_name,pass,confim_password,email;
AlertDialog builder;
private EditText name,mail,password,confirm_pass;
private Button register;
private BackgroungWorker backgroungWorker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
mail = (EditText) findViewById(R.id.email);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.pass);
confirm_pass= (EditText) findViewById(R.id.confirmpass);
register = (Button) findViewById(R.id.register_btn);
builder = new AlertDialog.Builder(this).create();
}
public void registerClicked(View view) // this is not working
{
if(view.getId()==R.id.register_btn)
{
if(name.getText().equals(""))
{
showMessage("Error","Name Cannot be left blank");
return;
}
if(mail.getText().equals(""))
{
showMessage("Error","Email Cannot be left blank");
return;
}
if(password.getText().equals(""))
{
showMessage("Error","Password Cannot be left blank");
return;
}
if(password.getText().equals(confirm_pass.getText().toString()))
{
backgroungWorker = new BackgroungWorker(this);
backgroungWorker.execute("Register",name.getText().toString(),password.getText().toString(),mail.getText().toString());
}
}
}
public void showMessage(String title,String message)
{
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(true);
builder.show();
}}
register.xml
`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
android:background=
android:backgroundTint="#02b864">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#02b864">
<ImageView
android:layout_width="212dp"
android:layout_height="176dp"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:background="#drawable/splash"
android:layout_marginTop="20dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp">
<EditText
android:layout_width="wrap_content"
android:layout_height="50dp"
android:hint="Name"
android:id="#+id/name"
android:drawableLeft="#drawable/ic_username"
android:drawableTint="#color/colorPrimaryDark"
android:drawablePadding="#dimen/activity_vertical_margin"
android:focusable="true"
android:background="#drawable/editext_bg_gray"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:singleLine="true"
android:layout_marginTop="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="50dp"
android:hint="Email"
android:id="#+id/email"
android:drawableLeft="#drawable/ic_username"
android:drawableTint="#color/colorPrimaryDark"
android:drawablePadding="#dimen/activity_vertical_margin"
android:focusable="true"
android:background="#drawable/editext_bg_gray"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:singleLine="true"
android:layout_marginTop="5dp"
/>
<EditText
android:inputType="textPassword"
android:ems="10"
android:id="#+id/pass"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:hint="Password"
android:drawableLeft="#drawable/ic_pwd"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTint="#color/colorPrimaryDark"
android:focusable="true"
android:background="#drawable/editext_bg_gray"
android:layout_gravity="center_horizontal"
android:layout_marginRight="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="5dp"
android:singleLine="true" />
<EditText
android:inputType="textPassword"
android:ems="10"
android:id="#+id/confirmpass"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:hint="Confirm Password"
android:drawableLeft="#drawable/ic_pwd"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTint="#color/colorPrimaryDark"
android:focusable="true"
android:background="#drawable/editext_bg_gray"
android:layout_gravity="center_horizontal"
android:layout_marginRight="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="5dp"
android:singleLine="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/register_btn"
android:onClick="registerClicked"
android:clickable="true"
android:layout_gravity="center_horizontal"
android:background="#e5e7e8"
android:text="Register"
android:src="#drawable/editext_bg_gray"
android:textColor="#0fbb6c"
android:singleLine="true"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="50dp"
android:textStyle="normal"
android:textAlignment="center"
android:textSize="22dp"
/>
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>`
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.umarsafdar.dev96.chat">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".Splash"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Register"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN">
<category android:name="android.intent.category.DEFAULT" />
</action>
</intent-filter>
</activity>
</application>
</manifest>
thanks in advance.