This question already has answers here:
How to run an activity only once like Splash screen
(5 answers)
Closed 1 year ago.
I have a Android App built in Android studio, on this app, I am using a Walkthrough Activity.
How can set this activity in a way that when a button is clicked, this page won't show again.
This is the function "public void onFinishButtonPressed()" and this is the part where I added onlick listener to the button, how should it be done in a way that once this function is called, this activity will not open again.
I have tried to implement a code to show activity only on first time run, but it is still not the desired result, i really want this page to keep showing until using clicks on that button.
Thanks for your help in advance.
My code;
package com.frigate.vpn.view;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.frigate.vpn.R;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughActivity;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughCard;
import java.util.ArrayList;
import java.util.List;
public class Walkthrough extends FancyWalkthroughActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FancyWalkthroughCard fancywalkthroughCard1 = new FancyWalkthroughCard("Welcome to Frigate Media VPN", "Let me show you why so many people love Frigate Media VPN", R.drawable.find_restaurant1);
FancyWalkthroughCard fancywalkthroughCard2 = new FancyWalkthroughCard("We Protect your Privacy", "Internet access is mind free, we'll keep you safe",R.drawable.pickthebest);
FancyWalkthroughCard fancywalkthroughCard3 = new FancyWalkthroughCard("Fast & Limitless!", "We provide you the fastest servers without limits.",R.drawable.chooseurmeal);
FancyWalkthroughCard fancywalkthroughCard4 = new FancyWalkthroughCard("Frigate Media VPN is 100% Free", "You do not have to worry about paying for expensive VPN, we give you everything for free.",R.drawable.mealisonway);
fancywalkthroughCard1.setBackgroundColor(R.color.white);
fancywalkthroughCard1.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard2.setBackgroundColor(R.color.white);
fancywalkthroughCard2.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard3.setBackgroundColor(R.color.white);
fancywalkthroughCard3.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard4.setBackgroundColor(R.color.white);
fancywalkthroughCard4.setIconLayoutParams(300,300,0,0,0,0);
List<FancyWalkthroughCard> pages = new ArrayList<>();
pages.add(fancywalkthroughCard1);
pages.add(fancywalkthroughCard2);
pages.add(fancywalkthroughCard3);
pages.add(fancywalkthroughCard4);
for (FancyWalkthroughCard page : pages) {
page.setTitleColor(R.color.black);
page.setDescriptionColor(R.color.black);
}
setFinishButtonTitle("Get Started");
showNavigationControls(true);
setColorBackground(R.color.white);
//setImageBackground(R.drawable.restaurant);
setInactiveIndicatorColor(R.color.grey_600);
setActiveIndicatorColor(R.color.colorGreen);
setOnboardPages(pages);
}
#Override
public void onFinishButtonPressed() {
Intent intent = new Intent(Walkthrough.this, MainActivity.class);
startActivity(intent);
finish();
}
}
Why not just use a global boolean variable named "isFinishedButtonPressed" set to false by default and when the button is pressed set it to true, and with the correct conditions it should do what you want, no ?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to play a sound on button click but it is giving a null pointer exception. I looked at some answers on StackOverflow but nothing helped
package com.example.testproject;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.dice_sound);
btn.setOnClickListener(v -> {
mp.start();
mp.release();
});
}
}
Error: As per the error showing in Logcat the variable mp is considered as null. I can't find out the fix for it.
The error is occurring because the sound .wav is not supported by the device that I am running on the test app. It is running on a different device that supports .wav file format. I have converted the file type to mp3 and now it is working on both devices.
Thanks to everyone for your reply...
Try this in your click listener
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(true);
try {
mediaPlayer.setDataSource(this, R.raw.dice_sound);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.start(); // if app craches on this line commit it then check
} catch (Exception e) {
e.printStackTrace();
}
Make sure that you should stop the mediaplayer before exist from the activity. You can do this in the click of the stop button. if you dont want to add the stop button then in the activity life cycle you should override onDestory and stop the player in the onDestory function.
I'm making a project in which I need to store a specific string in my application. I must be able to Store it, Delete it, and Modify it at any given time AFTER the user authenticates, which is done by using the fingerprint API.
If possible, I would like to make sure that ONLY the selected fingerprint, or ONLY the fingerprints that were in the phone before adding this string, will be able to unlock/reveal this string
pop-up windows in which I would like to have the password check for example is as follows:
package com.gmtechnology.smartalarm;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class Check_Pass extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.check_pass, null))
// Add action buttons
.setPositiveButton(R.string.check, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Check if the entered string matches the string stored
DialogFragment next = new Add_Pass();
next.show(getFragmentManager(), "Add_pass");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Check_Pass.this.getDialog().cancel();
}
});
return builder.create();
}
}
This pop-up has an edit text that I can capture the input from to use for the comparison, adding and removing will follow the same pattern. The point here and how to SAFELY store that string and manage it.
Safely store what?? Look if you want a persistent storage i.e you need to save it even after your application is closed .then you should use Shared Preference .. Its very easy to use and modify . Or if you want to save it only for once at the runtime of your application then just use a singleton class for it ..
As #ADM said use SharedPreference to store your String. You can specify if your data is private or public.
Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
Have a look at the docs or this answer here.
In your case, you can make a specific activity (to manipulate your string) only accessible with a Fingerprint authentification.
You should be aware that not all devices are compatible.
I'm wanting to add a button to the YouTubePlayerView but don't know the best way to go about doing so. I would like the button only to be present when the user clicks on the screen to bring up the youtube controls (play/pause, timeline, share, etc.) that fades away after a few seconds just as the controls fade. I've looked into ViewGroupOverlay but not sure if this is the best way to do so and I'm not sure how to only have the button added to the overlay when the controls are available. It feels like I have to override one of the YouTubePlayer or YouTubePlayerView functions to know when the controls are visible but I'm just making a hypothesis here. I'm relatively new to android and it's been a while since I've done anything serious in Java. Any direction here would be great if others don't know the exact answer. I've looked around for about 2 hours before posting this :)
package com.example.something.exampletube;
import android.os.Bundle;
import android.view.ViewGroupOverlay;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by Nicholas Dwyer on 4/17/2015.
* This class is used to play youtube videos
*/
public class PlayerActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView playerView;
ViewGroupOverlay groupOverlay;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_player);
playerView = (YouTubePlayerView) findViewById(R.id.player_view);
playerView.initialize(YoutubeConnector.KEY, this);
groupOverlay = playerView.getOverlay();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
if(!restored) {
youTubePlayer.cueVideo(getIntent().getStringExtra("VIDEO_ID"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
String errorMessage = "There was an error initializing the YouTubePlayer" + youTubeInitializationResult.toString();
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
//Toast.makeText(this,getString(R.string.failed), Toast.LENGTH_LONG).show();
}
}
It is not possible to add buttons as overlays above the player as specified by Google:
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayerView
Note that while videos are playing, this View has a minimum size of
200x110 dp. If you make the view any smaller, videos will
automatically stop playing. Also, it is not permitted to overlay the
view with other views while a video is playing.
See also here Is it possible to overlay some views on YouTube Android Player?
If any view only partially overlaps (or YouTubeVideoView is only partially scrolled outside the visible screen), the video is stopped after approximately one second. Google supposedly does that to prevent abuse of videos for advertising outside YouTube.
Alternatives: Use a WebView and embed it.
Another good alternative is to used Exoplayer, to overlay your video with view. It is not part of the android sdk, but it's recommended by google and included in android developer documentation :
http://google.github.io/ExoPlayer/
https://developer.android.com/guide/topics/media/exoplayer.html
Exoplayer allow you to stream any kind of video, not only Youtubes videos.
It's also good to mention that Exoplayer is used in Youtube application.
Instead of adding button as a layer above the player, you can add it INSIDE the player:
Button b = new Button(this);
b.setBackgroundResource(R.drawable.close);
((ViewGroup)((ViewGroup) youTubePlayerView.getChildAt(0)).getChildAt(0)).addView(b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Working for me.
The first splashscreen hidden after 5 secondes.
I want to add a second splashscreen like the first before enter in MainActivity.
in #drawable/background_1 <= This is the first image splashscreen I added.
in #drawable/background_2 <= I need to add this image in second splashscreen.
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_1" >
</RelativeLayout>
SplashScreen.java
package org.sbynight.app;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class SplashScreen extends Activity {
private static String TAG = SplashScreen.class.getName();
private static long SLEEP_TIME = 5; // Sleep for some time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
setContentView(R.layout.splash);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
private class IntentLauncher extends Thread {
#Override
/**
* Sleep for some time and than start new activity.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME*1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Start main activity
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(intent);
SplashScreen.this.finish();
}
}
}
Problem Solved - UPDATE OF POST -
1.I create a "SplashScreen2.java" + "Splash2.xml"
2.I added #drawable>background_2 (the second image of splashscreen)
3.I added to In Manifest splash2.....
In my SplashScreen.java, I deleted this code:
// Start main activity
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(intent);
SplashScreen.this.finish();
In my SplashScreen.java, Replace by this code :
/**** Create Thread that will sleep for 5 seconds ****/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 1 seconds
sleep(1*1000);
// After 1 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),SplashScreen2.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
In my Splashscreen2.java, I added the same code like SplashScreen.java,
Surely with this code now to start the MainActivity.class
// Start main activity
Intent intent = new Intent(SplashScreen2.this, MainActivity.class);
SplashScreen2.this.startActivity(intent);
SplashScreen2.this.finish();
Problems Solved! I have now 2 SplashScreen!
This use-case goes against the Android design guidelines.
Please think about how your users would get a good user experience using your app and get access to your content fast.
Designing Help into Your App
Don't show unsolicited help, except in very limited cases
Naturally, you want everyone to quickly learn the ropes, discover the
cool features, and get the most out of your app. So you might be
tempted to present a one-time introductory slideshow, video, or splash
screen to all new users when they first open the app. Or you might be
drawn to the idea of displaying helpful text bubbles or dialogs when
users interact with certain features for the first time.
In almost all cases, we advise against approaches like these because:
They're interruptions. People will be eager to start using your app,
and anything you put in front of them will feel like an obstacle or
possibly an annoyance, despite your good intentions. And because they
didn't ask for it, they probably won't pay close attention to it.
They're usually not necessary. If you have usability concerns about an
aspect of your app, don't just throw help at the problem. Try to solve
it in the UI. Apply Android design patterns, styles, and building
blocks, and you'll go a long way in reducing the need to educate your
users.
Source: http://developer.android.com/design/patterns/help.html
I don't really understand why you would want to add a second "splash screen". If you really did want to do it, why not make the MainActivity your SplashScreenActivity and then move onto a new activity from there.
I'm trying to use Google Analytics in my Android application with
Google Configuration
Add .jar in my project
Insert this in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Add this in my java file
public class MainActivity extends Activity {
GoogleAnalyticsTracker tracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = GoogleAnalyticsTracker.getInstance();
tracker.startNewSession("My-UA–XXXXXXXX", this);
setContentView(R.layout.main);
Button createEventButton = (Button)findViewById(R.id.NewEventButton);
createEventButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tracker.trackEvent(
"Clicks", // Category
"Button", // Action
"clicked", // Label
77); // Value
}
});
setContentView(R.layout.main);
Button createPageButton = (Button)findViewById(R.id.NewPageButton);
createPageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Add a Custom Variable to this pageview, with name of "Medium" and value "MobileApp" and
// scope of session-level.
tracker.setCustomVar(1, "Navigation Type", "Button click", 2);
// Track a page view. This is probably the best way to track which parts of your application
// are being used.
// E.g.
// tracker.trackPageView("/help"); to track someone looking at the help screen.
// tracker.trackPageView("/level2"); to track someone reaching level 2 in a game.
// tracker.trackPageView("/uploadScreen"); to track someone using an upload screen.
tracker.trackPageView("/testApplicationHomeScreen");
}
});
Button quitButton = (Button)findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Button dispatchButton = (Button)findViewById(R.id.DispatchButton);
dispatchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Manually start a dispatch, not needed if the tracker was started with a dispatch
// interval.
tracker.dispatch();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stopSession();
}
}
==> And it's ok, no error, compiling and executing but i have created my ua account yesterday (more 24h) and i have nothing in my google analytics panel.
My Question : is there an error in my code or i want to wait again ? Live trafic works for Android application (like tradicional website) ???
I have no information about Live trafic (when i play my app, i would like to show the number of person using my application) and Saved trafic (with viewed pages, time)
Thank you for your replies and excuse my poor english :)
bye
UPDATE 1 :
i've used this tuto : http://www.xatik.com/2012/03/27/how-to-use-google-analytics-in-android-applications/ and i've got this in my Logcat :
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): Host: www.google-analytics.com
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): User-Agent: GoogleAnalytics/1.4.2 (Linux; U; Android 2.2; en-us; sdk Build/FRF91)
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): GET /__utm.gif?utmwv=4.8.1ma&utmn=235327630&utme=8(1!Navigation%20Type)9(1!Button%20click)11(1!2)&utmcs=UTF-8&utmsr=240x320&utmul=en-US&utmp=%2FtestApplicationHomeScreen&utmac=BLIBLUBLIBLO–1&utmcc=more_and_more
in progress but nothing in my Live Analytics panel....
i've added EasyTracker .jar in my project
Here my Activity Code:
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.google.android.apps.analytics.easytracking.EasyTracker;
import com.google.android.apps.analytics.easytracking.TrackedActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends TrackedActivity {
GoogleAnalyticsTracker tracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button quitButton = (Button)findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EasyTracker.getTracker().trackEvent("ButtonClick", "MyButtonName", "", 0);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
//How can i stop the tracking onDestroy ???
}
}
I know this is a couple months old but I'll give a response to potentially help others. I am the person who wrote the guide that was referenced in Update 1 of the OP. One issue I originally ran into was the fact that I was using a custom ROM on my phone. A lot of custom ROMs have modified 'hosts' files that block an apps access to display ads or in this case blocks the sending of data to Google Analytics. If you do have a custom ROM on your phone, you can check the 'hosts' file to see if Google Analytics is listed in there. The fastest way to do this is to open the file in a text editor on your computer. To do this:
Get a file explorer app on you android device (I use 'ES File Explorer').
Navigate to '/etc'.
Locate and copy the 'hosts' file to a known location on your SD card.
Connect phone/SD card to computer and open the 'hosts' file in a text editor (Notepad++ is nice and free).
Search through file for anything that relates to Google Analytics and delete it. I first searched for 'analytics', went through all results, and deleted everything that had something to do with Google attached to the name (there are other analytic sites). Then I searched for 'google', went through all the results, and deleted anything that still related to Analytics.
Save 'hosts' file.
Disconnect from computer and use file explorer to copy the 'hosts' file from SD card back to '/etc' and overwrite.
This should allow your phone to send data to Google Analytics. I will update my guide to include this somewhere.