I am new to android and not able to figure out why app crashes when i add below code to play music when i tap on Image view (image).
Below is the main activity code.
ImageView one = (ImageView) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.cow);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});}
Below is the ImageView code in XML file
<ImageView
android:id="#+id/button1"
android:layout_width="350dp"
android:layout_height="400dp"
android:src="#drawable/tr"/>
MP3 file is placed under raw folder.
Please help me in fixing this issue. Thanks in advance.
App crashing because you imageview getting wrong id.
just replace this
ImageView one = (ImageView) this.findViewById(R.id.button1);
to
ImageView one = (ImageView)findViewById(R.id.button4);
also play audio file from Raw folder:
int resID=getResources().getIdentifier("YourAudioFileName", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();
don't forget to add permission in Manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Hope it will help you!!
Related
image
How to get this kind of animation in Android studio.
I am creating a quiz app. I want user to click a button and let the code check for answer and then change button animation as in the video.
Create a file in res folder with name alpha_animation
<?xml version="1.0" encoding="utf-8"?>
<alpha
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500"
android:fromAlpha="1"
android:toAlpha="0.05"
android:repeatCount="5"
android:repeatMode="reverse"
/>
now write this in you activity
private Button mButton;
private Animation mAlphaAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
mContext = getApplicationContext();
mActivity = MainActivity.this;
mButton = (Button) findViewById(R.id.btn);
mAlphaAnimation = AnimationUtils.loadAnimation(mContext,R.anim.alpha_animation);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Start the blink animation (fade in and fade out animation)
mButton.startAnimation(mAlphaAnimation);
}
});
}
I have not found a clear answer on this so I figured I would write a post to see if anybody can point me in the right direction.
Basically I am creating a Voice Notes application and I have set a 'delete' button for the locally saved files as a trash can image for an ImageButton. Seeing as users will be able to save as many audio files as they want I implemented a loop where the button is created, the ID is set via setID, and then a click listener is used based on the generated ID.
My problem is that the click listener works on the sides of the image, but not on the actual image, meaning if I click to the right or left of the ImageButton the file is deleted, however, when I actually click the trash can image in the ImageButton, nothing happens. I also have logs being registered anytime the button is clicked and they also don't work when I click the actual image, so I am sure the issue is that somehow the listener is not being used when the ImageButton is clicked. - Please remember that I said the click registers to the right and left of the image.
Here is the relevant code:
try{
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
//Button button = new Button(getApplicationContext());
TextView fileButton = new TextView(getApplicationContext());
fileButton.setTextColor(Color.parseColor("#ffffff"));
fileButton.setBackgroundResource(R.drawable.textview_button_colors);
fileButton.setTypeface(fileButton.getTypeface(), Typeface.BOLD);
fileButton.setText((i+1)+") "+listOfFiles[i].getName());
fileButton.setId(i);
fileButton.setPadding(10,10,10,10);//LTRB
fileButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout deleteButton = (RelativeLayout) inflater.inflate(R.layout.image_buttons, null);
deleteButton.setId(i+i);
Log.d(LOG_TAG, String.valueOf(deleteButton.getId()) );//WORKS AS EXPECTED
deleteButton.setGravity(Gravity.CENTER_HORIZONTAL);
TableRow horizontalButtonTableRow= new TableRow(getApplicationContext());
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin=0;int topMargin=15;int rightMargin=0;int bottomMargin=0;
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
horizontalButtonTableRow.setLayoutParams(tableRowParams);
horizontalButtonTableRow.addView(fileButton);
horizontalButtonTableRow.addView(deleteButton);
final String fileName = saveDirectory.toString() + File.separator +
listOfFiles[i].getName();
fileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(LOG_TAG, "should be playing audio");
MediaPlayer mediaPlayer = new MediaPlayer();
try {
Vibrator vib = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(25);
FileInputStream fis = new FileInputStream(fileName);
mediaPlayer.setDataSource(fis.getFD());
Log.d(LOG_TAG, fileName);
mediaPlayer.prepare();
} catch (Exception e) {
Log.d(LOG_TAG, String.valueOf(e));
}
mediaPlayer.start();
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Vibrator vib = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(25);
File deleteFile = new File(fileName);
deleteFile.delete();
savedFileLoader();
Log.d(LOG_TAG, fileName+": WAS DELETED");
} catch (Exception e) {
Log.d(LOG_TAG, String.valueOf(e));
}
}
});
verticalButtonContainerLayout.addView(horizontalButtonTableRow);
}//END IF
}//END FOR
}catch(Exception e){
Log.d(LOG_TAG,e.toString());
}
MORE INFO(but not used in final solution): If I change my code for the inflater to work like this the imageButton is no longer added to my view. I think this happens because I am forced to remove the image button from the original relative view.
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout deleteButtonLayout = (RelativeLayout)
inflater.inflate(R.layout.image_buttons, null);
ImageButton deleteButton =
deleteButtonLayout.findViewById(R.id.imageButton);
deleteButtonLayout.removeView(deleteButton);
deleteButton.setId(i+i);
If I opt not to use removeView I get this exception:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here is XML for imageButton in relative layout:
UPDATE: I have corrected my code based on the approved answer provided by #John Tribe. The "fix" was to set the RelativeLayout to clickable and at the same time setting the ImageButton to not be clickable. Doing this allowed my entire inflated layout to be clickable, which is exactly what I needed for this problem seeing as there was only 1 element in my inflated RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:clickable="true"
android:layout_height="match_parent">
<ImageButton
style="?android:attr/buttonBarStyle"
android:id="#+id/imageButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:adjustViewBounds="true"
android:clickable="false"
android:scaleType="center"
android:background="#drawable/trash"/>
</RelativeLayout>
You used RelativeLayout , You should use Image or ImageButton,but if you really want to use RelativeLayout , then in xml add android:clickable="true".
Another approach can be by finding ImageButton and setting listener.
ImageButton deleteButton = deleteButtonLayout.findViewById(R.id.imageButton);
deleteButton.setOnClickListener( new On...);
So I have two objects on my activity, a TextView, and a Button. I did change the font of both of these using a font style from my assets folder. The project would load fine no problems. However now all of a sudden changing the TextView font makes the game crash and not load. I can't understand what could have caused this and how to solve it other than maybe using a button to display text, which is in practical.
My java code:
public class Main_Menu extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__menu);
Button n=(Button) findViewById(R.id.start_button);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Stencil WW.ttf");
n.setText("Start");
n.setTypeface(typeface);
Typeface typeface2 = Typeface.createFromAsset(getAssets(), "Stencil WW.ttf");
TextView title = (TextView) findViewById(R.id.title);
title.setTypeface(typeface2);
//sets screen orientation on created
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
}
I did use the typeface to change both texts fonts but I tried just making it again with typeface2 and it still crashes. Not sure if I need to show any other part of my project but will if you wish to see it. Thank you for the help.
It seems like you forgot "setText" to the title
I am trying to develop an android app but I have some problems. I know a little bit about Java but I'm perfect with the XML part. I made an imagebutton and I want a browser to open a certain url when the user clicks on that button. Could someone please explain me how to do this step by step?
This is the button code taken from my main_activity.xml
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/donate"
android:src="#drawable/donate"
android:text="#string/about_link"
android:autoLink="all"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
Please remember that im not very good at Java so I will just copy and paste to my activitymain.java
Use this on imgebutton click listner
webview=(WebView)findViewById(R.id.webView1);
webview.loadUrl("http://www.google.com");
You could use something like that:
//any code
private ImageButton imageButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//Only if you will use for something else
imageButton = (ImageButton) findViewById(R.id.donate);
//any code
}
// any code
private void callBrowser(View view) {
String url = "http://www.example.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
//any code
And inside your xml add this attribute:
android:onClick="callBrowser"
I need to link the button with the page (not the main page) like when I click on the button to go to the page for example (location page)?
private void setupLocationPageButton() {
Button LocationPageButton = (Button) findViewById(R.id.btnLocationPage);
LocationPageButton.setOnClickListener(new View.OnClickListener()
If your goal is to open another activity this is what you are going to want to do.
In your xml file you are going to want something like this
...
<Button
android:id="#+id/activity_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButtonClicked"
android:text="#string/text_of_button" />
...
Then in your activity you want
public void onButtonClicked(View view) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
}
what i think you trying to do: is when you click on button it's change the MainActivity
Button LocationPageButton = (Button) findViewById(R.id.btnLocationPage);
LocationPageButton.setOnClickListener(new View.OnClickListener({
public void onClick(View _view) {
Intent i = new Intent(MainActivity.this,TheActivityTheclassNameYouWannGoTo.class);
startActivity(i);
}
}));
but first you have to creat activity and class inherit Activity like MainActivity
initialize the class in AndroidMainfest.xml
i hope this help you
You can use fragment, each fragment contains a specific page, see this for Android fragment.