Android Studio - Media Player: How do i prevent sound from overlapping? - android-studio

package com.example.sound;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
sound();
}
});
}
public void sound()
{
MediaPlayer mp = MediaPlayer.create(this,R.raw.mesa);
mp.start();
}
}
Right now, when i press the button WHILE the audio is playing, the second audio comes on and overlaps the first audio.
If i spam the button, there will be a lot of audio overlapping each other.
I only want one audio to be played at a single time. The first audio should stop if i press the button again.
How can i do this? I have seen some other relevant post but to no avail.

public void sound()
{
MediaPlayer mp = MediaPlayer.create(this,R.raw.mesa);
mp.start();
}
seems like you are creating a new instance of MediaPlayer each time the user clicks the button - thats why you hear multiple sounds. You should create a global instance of MediaPlayer, then in onClick method you should stop already played audio and start a new one.

Related

How to use 2 public classes, protected void on creat functions in the same fragments?

How to put more than one class,overview,void in MainActivity java of Android Studio? I need to have both the button and a code to make the map of google have some restricions in the same page. What names of the classes should be changed for it to work. The codes work when put independently but not together.How to make them work good together?
package com.example.maps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class FirstFragment extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFoodFragment();
}
});
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
}
public class MainACTIVITY extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mapAPI;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment =(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
#Override
public void onMapReady(GoogleMap googleMap){
mapAPI = googleMap ;
LatLng one = new LatLng(-21.754812, -48.219451);
LatLng two = new LatLng(-21.787443, -48.113332);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//add them to builder
builder.include(one);
builder.include(two);
LatLngBounds bounds = builder.build();
//get width and height to current display screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20);
mapAPI.setLatLngBoundsForCameraTarget(bounds);
mapAPI.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mapAPI.setMinZoomPreference(mapAPI.getCameraPosition().zoom);
LatLng Kampai = new LatLng(-21.780985, -48.186859);
mapAPI.addMarker(new MarkerOptions().position(Kampai).title("Kampai"));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Kampai));
}
}
Yes the can be in the same file but you have your mainACTIVITY inside your FirstFragment which cannot happen you need to remove the bottom most bracket and place it right above the start of your mainACTIVITY class, your FirstFragment's brackets need to close before you paste another class into the file.

Opening a new fragment from within a ViewPager in Android Studio

I have a question about opening a new fragment from within a ViewPager.
I setup FragmentA, FragmentB and FragmentC to be fragments of a viewpager and then proceeded to setup Fragment1 and Fragment2 as fragments of another viewpager which resides in FragmentB.
So Fragment1 and Fragment2 are in a viewpager which is essentially nested in another viewpager. I'm playing around with UI styles etc and this is is similar to that found in the Flickr app.
The problem I'm having is that once I get into the fragment1 or fragment2 (the nested fragment) I want to be able to click on something and enter a full screen fragment bypassing the toolbar I set up in FragmentB.
Below is the the code I have for FragmentB with the toolbar, tablayout and viewpager.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
public class FragmentB extends Fragment {
public FragmentB() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b,container,false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewPagerFragmentB);
ViewPagerAdapter adapter = new ViewPagerAdapter(((FragmentActivity) getContext()).getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"Fragment 1");
adapter.addFragment(new Fragment2(),"Fragment 2");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
// Inflate the layout for this fragment
return rootView;
}
}
Here is the code I've put together for fragment2 which contains a button I would like to take to take me to another fragment.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_2,container,false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new FragmentFull();
FragmentManager fm = ((FragmentActivity) getContext()).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragmentFullContainer,fragment);
ft.commit();
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Upon clicking the button the app crashes. I get the error:
No view found for id 0x7f080084 (com.app.fragmentdemo:id/fragmentFullContainer) for fragment FragmentFull
If I change the id of the fragment container to the id I assigned to the Fragment2 layout file, it works fine. However, this is still contained in the nested viewpager and doesn't allow me to enter a new layout.
I really appreciate your help.
Thanks.
In the following line
ft.add(R.id.fragmentFullContainer,fragment);
fragmentFullContainer should be a view in your R.layout.fragment_2
You are getting the crash because the OS cannot find fragmentFullContainer in R.layout.fragment_2
UPDATE
replace getSupportFragmentManager with getChildFragmentManager
If you want full screen , you have to manually hide Activity View elements.
Most probably, you have toolbar from activity, you can remove it like that.
((AppCompatActivity)getActivity()).getSupportActionBar().hide();

Android Studio - Creating a Loading/Splash Screen for WebView

I have followed through this tutorial (I am completely new to Android Studio): Loading/Splash Screen Tutorial
and I am unsure why my code isn't working correctly.
I get the loading circle come up on the app I have created, but it does not go away when the app loads the webpage.
I have gone over my code a few times now and I cannot see any errors (obviously there are some somewhere!) Just seems as if it isn't recognising that my webpage has loaded within the app.
Here is my code from my MainActivity.java file:
import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
String ShowOrHideWebViewInitialUse = "show";
private WebView myWebView;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
myWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setMinimumFontSize(1);
myWebView.getSettings().setMinimumLogicalFontSize(1);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("https://node-red-test.ftp21.net:1024/ui");
myWebView.setWebViewClient(new WebViewClient() { #Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){ handler.proceed(); } });
}
// This allows for a splash screen
// (and hide elements once the page loads)
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView myWebView, String url, Bitmap favicon) {
// only make it invisible the FIRST time the app is run
if (ShowOrHideWebViewInitialUse.equals("show")) {
myWebView.setVisibility(myWebView.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(myWebView.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
I am currently running Android Studio version 2.1.2 - due to problems with later versions that I came across when following another tutorial.
Thanks,

Android Studio Opening an activity

I am trying to open an activity with in an activity. I succeeded to do to from MainActivity but for some reason, this wont allow me to do so again.
I am very new to this, please help me.
package com.example.edonfreiner.siddur;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Davening extends AppCompatActivity {
Button shacharisButton, minchaButton, maarivButton;
public void openShacharis() {
shacharisButton = (Button) findViewById(R.id.shacharis);
shacharisButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open = new Intent(Davening.this, Shacharis.class);
startActivity(open);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_davening);
openShacharis();
}
}
This is the code to my class, there are no errors, meaning all buttons and references exist in the XML file.
Thank you in advance.
The logic you built is mistaken, cause you are calling a function in your onCreate that will not activate the onClick inside it. And when you click your object, it does not activate the onClick because this is encapsulated inside openShacharis. So the solution is to take off onClick from openShacharis, this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_davening);
shacharisButton = (Button) findViewById(R.id.shacharis);
shacharisButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openShacharis();
}
});
}
public void openShacharis() {
Intent open = new Intent(Davening.this, Shacharis.class);
startActivity(open);
}
All activities need to be registered on the Android Manifest.
As you stated on your comment, if you don't have it registered, it won't open.
This documentation will probably help you. In particular the part where it Adds the required <activity> element in AndroidManifest.xml.

MediaPLayer not stopping

I dont understand how to actually get this to work. My code is;
package com.example.user.medialert;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.io.IOException;
/**
* Created by User' on 9/24/2016.
*/
public class alert extends Activity {
final MediaPlayer Siren = new MediaPlayer() ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
MediaPlayer Siren = MediaPlayer.create(this, R.raw.alertsiren);
try {
Siren.prepare();
} catch (IOException e) {
e.printStackTrace();
}
Siren.start();
}
public void onClickOk1(View view) {
Siren.stop();
Intent intent = new Intent(alert.this, counter.class);
startActivity(intent);
}
}
The onClick changes the activity as it is supposed to however when I add the Siren.Stop(); code, 'Siren' is invalid, the error being cannot resolve symbol.
I have tried
MediaPlayer Siren = new MediaPlayer();
above the onCreate method, allowing siren to be used in the onClick, but it still doesn't stop playing the sound.
Any ideas?
EDIT
Added to show the code I have updated attempting to make final, and this now crashes the app.
Highlighting Siren under the onCreate method shows that the program isn't linking the Siren in the Siren.stop(); call

Resources